我正在尝试创建两个 React 项目:
React 组件库(只有没有工作应用程序的组件)
使用已创建组件的 SPA 应用程序(示例应用程序)
我想实现这样的文件夹结构:
-
./src
- 包含 React 组件的目录 -
./example
- 包含使用 ./src 组件的 SPA 应用程序
示例目录中有配置文件(最简单的 React + webpack 配置,没有 HMR 和其他东西):
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const aliases = require('./aliases.js');
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
}
]
},
resolve: {
alias: aliases
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
aliases.js
var path = require('path');
module.exports = {
'webpack-alias-react': path.resolve(__dirname, '../src')
};
babel.rc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
VSCode 别名配置在 jsconfig.json
中文件。
这是我的问题。
当./src/SimpleComponent
包含这样的代码:
const SimpleComponent = () => {
return 'string';
};
正在运行 npm run build
命令构建工作应用程序。
但是当./src/SimpleComponent
返回:
const SimpleComponent = () => {
return <div>abc</div>;
};
npm run buid
命令抛出异常:
ERROR in ../src/SimpleComponent.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: D:\Tranzystor\webpack-alias-react\src\SimpleComponent.js: Unexpected token (4:9)
如何解决这个 webpack/Babel 配置问题?
为什么可以写<div>
在 App.js
?
这是正确的做法吗?
整个代码是here可用。
最佳答案
我已经解决了 Babel 7
的问题,并且有针对此类问题的扩展解决方案:
github
准备使用webpack 4 + React + Babel 7 + eslint
配置。
它对 monorepo 解决方案很有帮助。
将自己的组件库发布到npm可以是另外一种应用。正如我上面提到的,./src
目录包含小的 React 组件(你想在 npm 上发布的内容)。在 ./demo
目录中有一个 spa 应用程序,它展示了如何使用提供的组件(例如它可以是故事书)。
关于javascript - 使用别名配置 Webpack 4,Babel 7 构建 React 组件库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52597362/