optimizationwebpackcode-splitting

how to optimise webpack bundle to split code into smaller files


I want to optimise the javascript pages being served. i am using webpack 4 and have the following configuration. i webpack using webpack -p --mode=production. when i webpack in production mode i still get files greater than 1 mb. i want to reduce the file size as much as possible for performance.

module.exports = {
    entry : {
        app: [...
        ],
        vendor: ['react','moment','lodash/core']
    },
    output : {
        filename : '[name].bundle.js',
        path : __dirname + '/docs',
        publicPath : '/'
    },
    optimization: {
         splitChunks: {
           chunks: 'all',
           cacheGroups: {
              vendor: {
                chunks: 'initial',
                name: 'vendor',
                test: 'vendor',
                enforce: true
              },
            }
         },
         runtimeChunk: true,
         minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    },
    module : {
        rules : [  {
            test : /\.js[x]?$/,
            loader : 'babel-loader',
            exclude : {
                  test: /node_modules/,
                  not: [/@babel\/register/],
                },
            options : {
                cacheDirectory : false,
                presets : [ '@babel/preset-react' ],
                plugins : [ '@babel/plugin-transform-runtime' ],
            }
        }, {
            test : /\.css$/,
            use : [ {
                loader : MiniCssExtractPlugin.loader,
                options : {
                    publicPath : __dirname + '/docs/stylesheets',
                    hmr : process.env.NODE_ENV === 'development',
                },
            }, 'css-loader', ]
        }, ...]
    },...
    plugins : [ 
        new HtmlWebpackPlugin({
            template : __dirname + '/src/index.html',
            filename : 'index.html',
            inject : true
        }),...
        new MiniCssExtractPlugin({
            filename : '[name].css',
            chunkFilename : '[id].css',
            ignoreOrder : false, 
        }), 
        new LodashModuleReplacementPlugin
    ],
};

Solution

  • You can use compression to further reduce bundle size. And then let your clients choose the compression they support e.g. Brotli, gzip.

    how to optimise webpack bundle to split code into smaller files

    One way of achieving that is to split React SPA into multiple SPAs, each with its own and smaller bundle. The dependencies would be separated into another 'vendor' bundle that gets reused. Also ensure the bundles are cached to increase performance.

    Crisp React demonstrates all those techniques. I'm the author.