【发布时间】:2020-01-23 07:49:32
【问题描述】:
背景
在我的项目中,我使用lerna js 来管理monorepo 文件夹结构和安装过程。文件夹结构很简单,我们有两个包,分别叫web和common。
package.json
lerna.json
packages
common
package.json
web
package.json
next.config.js
.babelrc
问题
为了避免每次在common 包中开发时都构建dist 版本,我在用于编译js 代码的webpack 规则中添加了include 属性。这完美无缺。
但问题是,当我想为从common 导入的代码添加别名时,编译时它不会应用它。我需要实现的代码需要添加此别名才能工作 (react-native-web-maps)。
一些可能相关的问题
- Babel 7 ignores files outside of project directory
- Plugin don't resolve aliases out side working directory
- Webpack with babel-loader don't process js files from sibling directories
- Config: Rule test should respect module alias
尝试过的解决方案
我已经尝试了好几天才能让它工作,但到目前为止还没有成功。以下是我到目前为止尝试过的事情:
- 使用next-transpile-modules plugin 和next-plugin-custom-babel-config 将
babel.config.js添加到根目录 - 将
alias添加到next.config.js中的webpack 配置,在web中有效,但不适用于从common导入文件 - 摆弄
root和rootMode(我对如何正确使用它们没有真正的了解)
代码 sn-ps
next.config.js(next.js 的 webpack 选项)
const path = require("path");
const withPlugins = require("next-compose-plugins");
const withImages = require("next-images");
const aliases = {
common: path.join(__dirname, "../common/"),
"react-native": "react-native-web",
"react-native-maps": "react-native-web-maps"
};
const includePaths = [path.resolve(__dirname, "../common/")];
const nextConfig = {
webpack: (config) => {
// Add aliases
config.resolve.alias = {
...(config.resolve.alias || {}),
...aliases
};
// Also transpile files from common/...
config.module.rules = config.module.rules.map((rule) => {
rule.include = [...(rule.include || []), ...includePaths];
return rule;
});
return config;
}
};
module.exports = withPlugins([withImages], nextConfig);
.babelrc
{
"presets": ["next/babel"],
"plugins": [
[
"module-resolver",
{
"root": ["./", "./../common/"],
"alias": {
"react-native": "react-native-web",
"react-native-maps": "react-native-web-maps",
"common": "./../common/src/"
}
}
]
]
}
packages/common/src/component.js
import React from "react";
import { View } from "react-native-web";
import MapView from "react-native-maps";
const Component = ({ coordinates }) => (
<View>
<MapView region={{ latitude: coordinates.latitude, longitude: coordinates.longitude }}>
<MapView.Marker
coordinate={{
latitude: coordinates.latitude,
longitude: coordinates.longitude
}}
/>
</MapView>
</View>
);
【问题讨论】:
-
您好,您是否以某种可以分享的方式解决了这个问题?