Abhi_7
Abhi_7

Reputation: 31

Reduce webpack bundle size in react.js

I am setting up my webpack config for a react app. But I am not able to reduce the size of bundle.js. In development mode the size is around 4MB and in production mode the size is around 1.5MB. Here is my config:-

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;
}

Please help me out in reducing the size of bundle.js. Thanks in advance :)

Refer: Bundle size in dev mode

Refer: Bundle size in prod mode

Script to run dev webpack-dev-server --config ./webpack.config.js --mode development --open --hot

Script to run prod webpack --config ./webpack.config.js --mode production --open --hot

Upvotes: 2

Views: 7837

Answers (2)

mpen
mpen

Reputation: 282875

Try adding

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

under plugins. React specifically eliminates a lot of debug code if you set that. Other libs may or may not look for it.


This is possibly rolled into the newish mode option, the docs have changed a bit since I last looked.

Upvotes: 1

winwiz1
winwiz1

Reputation: 3164

Bundle size 3.11MB in dev doesn't look too bad.
To further descrease the bundle size in production:

  • perform bundle minification
  • remove source maps
  • compress the bundle using gzip and Brotli and then let clients choose the compression

Upvotes: 0

Related Questions