我设置了具有文件结构的monorepo:
/root
/-ProjectA
/-ProjectB
/-common
在/ ProjectA中,我有一个React应用,该应用从/ common导入文件。当我尝试在Webpack Dev Server中启动它时,从Babel-Loader收到一条错误消息,提示导入的JSX所在的公用文件中存在编译错误。
如果我将通用文件移到ProjectA并从那里导入,那么一切正常,因此该特定文件没有问题(此外,这是一个非常简单的示例)。
/common/index.js(这是此目录中唯一的文件)
import React from 'react';
export default () => <span>Hello, World!</span>;
/ProjectA/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from '../common';
const App = () => <div><Hello /></div>;
ReactDOM.render(<App />, document.querySelector('#root'));
/ProjectA/.babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
/ProjectA/webpack.config.js
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: [
path.resolve('.'),
path.resolve('../common'),
],
use: {
loader: 'babel-loader'
}
}
/ProjectA/package.json
{
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"@babel/core": "^7.5.4",
"@babel/preset-env": "^7.5.4",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.35.3",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "^3.7.2"
}
}
为什么babel无法从当前目录之外的文件进行转译?有没有解决的办法,或者我的配置有问题?
答案 0 :(得分:0)
将此行添加到webpack.config.js
devServer: { contentBase: path.join(__dirname, "public") }
将此脚本添加到package.json
"scripts":{
"dev-server": "webpack-dev-server",
}
现在此命令应运行您的应用程序。
npm run dev-server