减少React.js中的Webpack捆绑包大小

时间:2019-09-24 06:29:25

标签: javascript reactjs webpack bundle webpack-dev-server

我正在为React应用设置我的webpack配置。但是我无法减小bundle.js的大小。在开发模式下,大小约为4MB,在生产模式下,大小约为1.5MB。这是我的配置:-

const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')

var config = {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: [/.css$/],                
        use:[                    
         'style-loader',                  
         'css-loader'
        ] 
      },
      {
        test: /\.(png|jpg|gif|jpeg|svg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'assets/images'
            }
          }
        ]
      }
    ]
  },
  devtool: 'source-map',
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: 'bundle.js'
  },
  devtool: 'source-map',
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      template: 'index.html'
    })
  ],
  devServer: {
    contentBase: './dist',
    hot: true,
    port: 3000,
    historyApiFallback: true
  }
}
module.exports = (env, argv) => {
  if (argv.mode === 'development') {
    config.plugins = config.plugins.concat([
        new BundleAnalyzerPlugin(),
      ])
  }
  if (argv.mode === 'production') {
    config.plugins = config.plugins.concat([
        new CleanWebpackPlugin(),
      ])
  }
  return config;
}

请帮助我减少bundle.js的大小。在此先感谢:)

引用:Bundle size in dev mode

引用:Bundle size in prod mode

运行dev的脚本 webpack-dev-server --config ./webpack.config.js --mode开发--open --hot

运行产品的脚本 webpack --config ./webpack.config.js --mode生产--open --hot

2 个答案:

答案 0 :(得分:1)

尝试添加

        new DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify("production"),
        }),

plugins下。如果您进行设置,React专门消除了许多调试代码。其他库可能会也可能不会寻找它。


这可能会套用到新的mode选项中,the docs自从我上次看过以来有所改变。

答案 1 :(得分:0)

开发中的捆绑包大小3.11MB看起来还不错。
为了进一步减少生产中的捆束尺寸:

  • 执行包最小化
  • 删除源地图
  • 使用gzip和Brotli压缩捆绑包,然后让客户端选择压缩方式
相关问题