带有死代码消除功能的 Webpack 树抖动是否适用于 node_modules?

B.G*_*ill 5 uglifyjs ecmascript-6 webpack material-ui tree-shaking

考虑到这个Webpack 3.8.1配置。

// common
module.exports = {
        context: path.resolve(__dirname, './src'),
        entry: [
            'whatwg-fetch',
            './index'
        ],
        output: {
            path: path.resolve(__dirname, 'build/assets'),
            publicPath: '/assets/',
            filename: 'main.js'
        },
        plugins: [
            new CleanWebpackPlugin(['build']),
        ],
        module: {
            rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            }, {
                test: /\.(scss|css)$/,
                use: [{
                    loader: 'style-loader'
                }, {
                    loader: 'css-loader'
                }, {
                    loader: 'sass-loader'
                }],
            }, {
                test: /\.(png|jpg|gif|woff2|woff)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192
                        }
                    }
                ]
            }]
        }
    };

//prod
module.exports = merge(common, {
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new UglifyJSPlugin()
    ],
    devtool: 'none'
});
Run Code Online (Sandbox Code Playgroud)

和这个Babel 6.26.0配置

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            ">1%"
          ]
        }
      }
    ], [
      "react"
    ]
  ],
  "plugins": [
    "transform-class-properties",
    "transform-export-extensions",
    "transform-object-rest-spread",
    "react-hot-loader/babel"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我期待树抖动与死代码消除一起UglifyJS工作,这种方式使我能够从index.es.js模块中编写命名导入,例如Material-UI-Icons,从包中删除未使用的导入。

import {Menu} from 'material-ui-icons';
Run Code Online (Sandbox Code Playgroud)

该库确实将 package.json 中定义的 ES6 模块重新导出为"module": "index.es.js".

然而,导入单个图标后,我的包大小增加了 0.5MB。当我把它改成

import Menu from 'material-ui-icons/Menu;
Run Code Online (Sandbox Code Playgroud)

仅导入此图标后,捆绑包大小再次减小。

我的配置是否有问题,或者我是否误解了摇树的工作原理并且不适用于这种情况?

B.G*_*ill 5

因此,经过一些额外的挖掘,我找到了原因/临时解决方案/解决方案。基本上,因为ES Modules可能会产生副作用,Webpack也不能安全地(根据规范)删除通常在或类似UglifyJS中找到的未使用的再导出index.es.js"module"

目前,有一些方法可以解决这个问题。您可以仅手动导入必要的模块,也可以使用babel-plugin-direct-import

好消息是通过标志Webpack 4添加了对纯模块的支持side-effects。当库作者将其标记为纯时,树摇动和缩小将按预期工作。我还建议阅读这篇精彩的总结

现在,我建议使用这个精彩的可视化工具手动处理您的包,并决定如何单独处理每个大的依赖项。