Optimising-Your-Application- bundle-size-with-webpack, which belongs to the React Primer and Best Practices series of The Author’s Web Front-end primer and Best Practices. I translated this article to improve the content of my own technical system, but I recommend visiting the Webpack website directly. Here are a few simple steps to optimize your React application package.

Recently I was building a one-page app based on React, and when I checked my site with Google TestMySite, it reported that it took too long to load, so I started thinking about how to optimize the package size for the first download. The first step in optimizing an application package is to review the current package composition and determine which dependencies are required. We can see the current package size in the Webpack echo:

$webpack -p -- Progress Hash: dbce3735c9520e2DC682 Version: webpack 1.14.0 Time: 54264ms Asset Size Chunks Names dist/index.js 3.29 MB 0 [emitted] main dist/index.js.map 13.7 MB 0 [emitted] main [0] multi main 40 bytes {0} [built] + 1374 hidden modulesCopy the code

Analyze inclusion dependencies

Here we use Webpack-bundle-Analyzer to analyze the package composition generated by WebPack and provide visual feedback to developers. We can use NPM to install the plugin:

$ npm install --save-dev webpack-bundle-analyzer
Copy the code

Then we need to modify webpack.config.js to introduce the plug-in:

var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// ...
plugins: [new BundleAnalyzerPlugin()]
// ...
Copy the code

After we compile with Webpack as usual, the visual results will be displayed at http://localhost:8888/, where you can probably see the following interface: The interactive plugin should help you analyze which dependencies dominate the package size. It also reminds us that when introducing a feature, we should only introduce the required modules, such as Lodash:

//1. Import the entire lodash library and add it to the bundle
import lodash from 'lodash'
lodash.groupBy(rows, 'id')

//2. Import only the required function from lodash
import groupBy from 'lodash/groupBy'
groupBy(rows, 'id')
Copy the code

Set the appropriate Node environment variables

Setting the appropriate environment variables can help Webpack better compress the code that handles dependencies. We need to set NODE_ENV to production in the production environment:

plugins: [...
    new webpack.DefinePlugin({
             'process.env.NODE_ENV': '"production"'
    }),
..]
Copy the code

Use minimal SourceMap

When we combine compressed JavaScript files in production, Webpack generates a SourceMap file for us to map the contents of the source file. Devtool is often set to eval in development environments, which packages a lot of code into the output body to speed up compilation. In the development environment, we can set the package size to eval-source-map or cheap-module-source-map.

$webpack -p -- Progress Hash: 68a52FDDBCC2898a5899 Version: webpack 1.14.0 Time: 29757ms Asset Size Chunks Names dist/index.js 1.71 MB 0 [emitted] Main dist/index.js.map 464 bytes 0 [emitted] main [0] multi main 40 bytes {0} [built] + 1365 hidden modulesCopy the code

Other common plug-ins

Here are a few common plugins that can be used to reduce package size, optionally based on project requirements:

  • Compression -webpack-plugin: This plug-in can compress resource files into.gz files and load them on demand according to the client’s needs.

  • Dedupeplugin: Extracts the same or similar files or code from the output package. It may be a burden on Entry Chunk, but it can effectively reduce the size of the package.

  • Uglifyjsplugin: Compressed output block size, refer to the official documentation.

  • Ignoreplugin: Used to ignore unnecessary content in the import module, e.g. when we introduced moment.js, we didn’t need to introduce all the locales in the library, so we can use this plug-in to ignore unnecessary code.

. var CompressionPlugin = require("compression-webpack-plugin"); . let config = { entry: path.join(__dirname, '.. /app/index'), cache: false, devtool: 'cheap-module-source-map', plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false, // Suppress uglification warnings pure_getters: true, unsafe: true, unsafe_comps: true, screw_ie8: true }, output: { comments: false, }, exclude: [/\.min\.js$/gi] // skip pre-minified libs }), new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]), new webpack.NoErrorsPlugin(), new CompressionPlugin({ asset: "[path].gz[query]", algorithm: "gzip", test: /\.js$|\.css$|\.html$/, threshold: 10240, minRatio: 0 }) ... ] .Copy the code

After the introduction of this plug-in, the volume of the package will be further compressed:





$webpack -p -- Progress Hash: 68a52FDDBCC2898a5899 Version: webpack 1.14.0 Time: 29757ms Asset Size Chunks Names dist/index.js 1.54 MB 0 [emitted] main dist/index.js.gz 390 KB 0 [emitted] main dist/index.js.map 464 bytes 0 [emitted] main [0] multi main 40 bytes {0} [built] + 1365 hidden modulesCopy the code