我只从 semantic-ui-react 导入一个组件
import { Button as SemanticButton} from 'semantic-ui-react';
但是在运行 webpack -p
之后,我在 bundle 中看到了来自 Semantic UI 的所有组件,它的大小超过 300KB(如果没有 Semantic UI,大约 30KB)。
我安装了所有最新版本:webpack@4.14.0; semantic-ui-react@0.81.3
这是我的 webpack.config.js
module.exports = {
entry: './src/index.js',
resolve: {
modules: [
path.resolve('./'),
'node_modules',
],
extensions: ['*', '.js', '.jsx', '.css', '.less'],
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
externals: {
react: {
root: 'React',
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
},
'react-dom': {
root: 'ReactDOM',
commonjs: 'react-dom',
commonjs2: 'react-dom',
amd: 'ReactDOM',
},
'prop-types': {
root: 'PropTypes',
commonjs: 'prop-types',
commonjs2: 'prop-types',
amd: 'PropTypes',
},
},
};
我做错了什么吗?如何使 tree shaking 与 semantic-ui-react 一起工作?我不想看到 bundle 中未使用的组件。
最佳答案
这个问题的解决方案变得相当简单。你只需要正确配置 Babel 即可。
Simply specifying
"modules": false
in your babel-preset-env config gets Babel to behave how we want, which allows webpack to analyze your dependency tree and shake off those unused dependencies. Furthermore, this process doesn't cause compatibility issues, as webpack ends up converting your code into a format that's widely compatible, anyway.
所以 .babelrc
可以看起来像这样:
{
"presets": [
["env", {
"modules": false
}]
]
}
关于javascript - 摇树不适用于 webpack 4 和 semantic-ui-react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51175095/