Webpack在打包时会出现重复引用的包

3
这是bundle-analyzer的输出:

enter image description here

正如您所看到的,像react-dom、jquery和mobx这样的包都在shell bundle和vendor bundle中。是否可能只将它们放在vendor bundle中? 更新 以下是配置文件:
entry: {
    shell: './src/shell.ts',
    vendor: [
      'jquery',
      'react',
      'react-dom',
      'react-router',
      'mobx',
      'mobx-react',
      'toastr',
      'styled-components',
    ],
  },
  output: {
    path: __dirname + '/dist',
    filename: '[name]bundle.js?[hash:8]',
    publicPath: '/',
  },
  devtool: PROD ? false : 'source-map',
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.json'],
    modules: ['node_modules'],
  },
  optimization: {
    minimize: !!PROD,
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    }),
    new ExtractTextPlugin('[name].css?[hash:8]', {
      allChunks: true,
      disable: !PROD,
    }),
    new HtmlWebpackPlugin({
      chunksSortMode: 'dependency',
      template: './src/index.tpl.html',
    }),
    new BundleAnalyzerPlugin(),
  ],
  

你能展示一下你的webpack配置文件吗? - dhruw lalan
当然,我更新了我的问题。(我没有包括“模块”对象) - stahlhammer
2个回答

7

您可以使用splitChunks优化Webpack设置,将所有来自node_modules文件夹的供应商代码拆分为单个vender捆绑包文件。

首先,从您的entry中删除vendor

然后,在您的config文件中添加以下代码:

optimization: {
    splitChunks: {
        cacheGroups: {
            vendors: {
                test: /[\\/]node_modules[\\/]/ ,
                name: 'vendor' ,
                chunks: 'all' ,
                enforce: true ,
            }
        }
    }
}

1

您正在使用entry手动拆分代码,这种方法存在一些缺陷,例如

如果入口块之间存在重复的模块,它们将被包含在两个捆绑包中。

您可以使用Entry dependenciesSplitChunksPlugin 来避免这种情况。

以下是Entry dependencies的示例:

entry: {
    shell: {import: './src/shell.ts', dependOn: 'vendor'},
    vendor: [
      'jquery',
      'react',
      'react-dom',
      'react-router',
      'mobx',
      'mobx-react',
      'toastr',
      'styled-components',
    ],
  },

由于您将在同一HTML页面中使用两个入口点,请记得启用optimization.runtimeChunk: 'single'

webpack代码拆分指南上有详细的解释,您也可以在那里阅读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接