Webpack 4包优化,代码拆分-React / Redux应用

时间:2018-08-15 10:47:37

标签: javascript reactjs optimization webpack webpack-4

我正在尝试减小bundle.js的大小。这是我用于生产的webpack配置:

module.exports = () => {
  return {
    entry: ['babel-polyfill', './src/app.js'],
    output: {
      path: path.join(__dirname, 'public', 'dist'),
      filename: 'bundle.js',
      chunkFilename: '[name].js'
    },
    optimization: {
      runtimeChunk: true,
      splitChunks: {
      chunks: 'all',
      minSize: 50000,
      maxSize: 250000,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          priority: -10
        },
      }
    },
    minimizer: [
      new UglifyJSPlugin({
        uglifyOptions: {
          parse: {
            ecma: 8,
          },
          compress: {
            ecma: 5,
            warnings: false,
            comparisons: false,
          },
          mangle: {
            safari10: true,
          },
          output: {
            ecma: 5,
            comments: false,
            ascii_only: true,
          },
        },
        cache: true,
        parallel: true,
        sourceMap: true
      }),
      new OptimizeCSSAssetsPlugin({})
    ]
    },
    module: {
      rules: [{
        loader: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },{
        test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader']
      }]
    }, 
    plugins: [
    new webpack.DefinePlugin({/*env variables*/}),
    new MiniCssExtractPlugin({
      filename: 'styles.css',
    }),
    new HtmlWebpackPlugin({ template: 'index.ejs', filename: path.join(__dirname, 'public', 'index.html')}),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ],
    devtool: 'source-map'
  };
};

我的应用的结构类似于经典的React / Redux应用:

|-src
|-|-app.js
|-|-actions
|-|-components
|-|-helpers
|-|-routers
|-|-selectors
|-|-store

使用此webpack配置,我设法将css提取出来并分成最大250kb的块。我也减少了片刻的大小。 经过所有这些努力,我的入口点仍然是583Kb。

Webpack screenshot

我还能做什么? 我尝试了延迟加载应用程序的一部分,但没有成功。因此,如果您有一个React应用程序的延迟加载示例,那就太好了。

1 个答案:

答案 0 :(得分:0)

我有webpack 6.0.1。基于documentation,我使用以下插件:

  1. webpack.optimize.ModuleConcatenationPlugin()-合并作用域 将所有模块合并到一个闭包中,并允许您的代码具有 在浏览器中更快的执行时间
  2. webpack.HashedModuleIdsPlugin()-导致哈希基于 模块的相对路径,生成四个字符串作为 模块ID
  3. webpack.optimize.OccurrenceOrderPlugin()-更改 id的分布以获得经常使用的最小id长度 ID
  4. webpack.NoEmitOnErrorsPlugin()-跳过发射阶段 只要编译时有错误。这样可以确保没有 发出包含错误的资产

我测试过,对webpack.config.js使用以下配置思路。您可以针对以下设置测试您的配置:

//webpack.config.js
module.exports = {
  ...
  devtool: 'cheap-module-source-map',
  ...
  plugins : [
    ...
    new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.HashedModuleIdsPlugin({
      hashFunction: 'sha256',
      hashDigest: 'hex',
      hashDigestLength: 4
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],

  ...

  optimization: {
    namedModules: false,
    namedChunks: false,
    nodeEnv: 'production',
    flagIncludedChunks: true,
    occurrenceOrder: true,
    sideEffects: true,
    usedExports: true,
    concatenateModules: true,
    splitChunks: {
      cacheGroups: {
        commons: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendor',
            chunks: 'all'
        }
      },
      minSize: 30000,
      maxAsyncRequests: 5,
      maxAsyncRequests: 3,      
    },
    noEmitOnErrors: true,
    minimize: true, 
    minimizer: [
      // we specify a custom UglifyJsPlugin here to get source maps in production
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        uglifyOptions: {
          compress: false,
          ecma: 6,
          mangle: true
        },
        sourceMap: true
      })
    ],
    removeAvailableModules: true,
    removeEmptyChunks: true,
    mergeDuplicateChunks: true,    
  },
...
}