1. Webpack usage background
- As front-end projects gradually expand, performance problems will inevitably occur. Especially in large and large-scale and complex projects, the front-end business may cause the entire page to stutter or even crash due to a small data dependency.
- Generally, after the project is completed, it will be packaged through webpack. Using webpack to optimize the performance of front-end project is a very important link.
2. How to optimize webpack
The methods of optimizing the front-end through webpack include: JS code compression, CSS code compression, Html file code compression, file size compression, picture compression, Tree Shaking, code separation, and inline chunk.
1. JS code compression
Terser is a JavaScript tool set for explanations, meat grinders, and compressors. It can help us compress and vilify our code and make the bundle smaller. In production mode, webpack uses TerserPlugin by default to process our code. If you want to configure it in a custom way, the configuration method is as follows:
const TerserPlugin = require('terser-webpack-plugin') = { ... optimization: { minimize: true, minimizer: [ new TerserPlugin({ parallel: true // Computer CPU core number -1 }) ] } }
Code compression
CSS compression usually removes useless spaces, etc., because it is difficult to modify selectors, attribute names, values, etc. For CSS compression, we can use another plug-in: css-minimizer-webpack-plugin.
// npm install css-minimizer-webpack-plugin -D const CssMinimizerPlugin = require('css-minimizer-webpack-plugin') = { // ... optimization: { minimize: true, minimizer: [ new CssMinimizerPlugin({ parallel: true }) ] } }
3. HTML file compression
When using the HtmlWebpackPlugin plugin to generate HTML templates, html optimization is performed by configuring the attribute minify.
= { ... plugin:[ new HtmlwebpackPlugin({ ... minify:{ minifyCSS:false, // Whether to compress css collapseWhitespace:false, // Whether to collapse spaces removeComments:true // Whether to remove comments } }) ] }
4. File size compression
Compress the file size to reduce broadband loss during http transmission.
// npm install compression-webpack-plugin -D new ComepressionPlugin({ test:/\.(css|js)$/, // Which files need to be compressed threshold:500, // Set how big the file is to start compressing minRatio:0.7, // At least compressed ratio algorithm:"gzip", // The compression algorithm used})
5. Picture compression
Generally speaking, after packaging, the size of some image files is much larger than that of js or css files, so image compression is more important.
module: { rules: [ { test: /\.(png|jpg|gif)$/, use: [ { loader: 'file-loader', options: { name: '[name]_[hash].[ext]', outputPath: 'images/', } }, { loader: 'image-webpack-loader', options: { //Compress jpeg configuration mozjpeg: { progressive: true, quality: 65 }, // Use imagemin**-optipng to compress png, enable: false to close optipng: { enabled: false, }, // Use imagemin-pngquant to compress png pngquant: { quality: '65-90', speed: 4 }, //Compress gif configuration gifsicle: { interlaced: false, }, // Turn on webp, and the jpg and png images will be compressed into webp format webp: { quality: 75 } } } ] }, ] }
6. Tree Shaking
Tree Shaking is a term that means eliminating dead code in a computer, relying on static syntax analysis of ES Module (no code is executed, and the dependencies of the module are explicitly known). There are two different solutions to implement Tree Shaking in webpack: useExports (by marking whether certain functions are used, and then optimized through Terser); sideEffects (skipping the entire module/file), directly checking whether the file has side effects.
usedExports only needs to set usedExports to true; after use, unused harmony export mul comment will be added to the webpack package to inform Terser that this code can be deleted during optimization.
= { ... optimization:{ usedExports:true; } }
The sideEffects configuration method sets the sideEffects property. If sideEffects is set to false, it tells webpack to safely delete unused exports. If some files need to be preserved, they can be set as an array.
"sideEffecis":[ "./src/util/", "*.css" // All css files]
7. Code separation
Separate the code into different bundles, and then load the files as needed, or load them in parallel. By default, all JS codes are loaded on the home page, which will affect the loading speed of the home page. The code can separate smaller bundles and control the priority of resource loading, providing code loading performance. Implemented through the plugin splitChunksPlugin.
= { ... optimization:{ splitChunks:{ chunks:"all" } } }
8. Inline chunk
You can embed some chunk modules into html through the InlineChunkHtmlPlugin plugin
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin') const HtmlWebpackPlugin = require('html-webpack-plugin') = { ... plugin:[ new InlineChunkHtmlPlugin(HtmlWebpackPlugin,[/runtime.+\.js/] }
9. Use CDN to accelerate and extract public third-party libraries
3. Summary
- Compressed code: delete unnecessary code, comments, simplify the writing of code, and so on. You can use webpack's UglifyJsPlugin and ParallelUglifyPlugin to compress JS files, and use cssnano (css-loader?minimize) to compress css
- Using CDN acceleration: During the construction process, modify the referenced static resource path to the corresponding path on the CDN. You can use webpack to output parameters and the publicPath parameters of each loader to modify the resource path
- Tree Shaking: Delete fragments that will never be reached in the code. It can be achieved by appending the parameter --optimize-minimize when starting webpack
- Code Splitting: chunk code by routing dimension or component (chunk), so that it loads on demand, and makes full use of browser cache
- Extract public third-party libraries: SplitChunksPlugin plugin to extract public modules, and use browser cache to cache these public codes that do not require frequent changes.
This is the end of this article about how JavaScript webpack module packer optimizes front-end performance. For more related JavaScript webpack content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!