Let’s move on to optimizing the quality of the packaged output file, i.e. making the packaged file as small as possible so that we can load the file faster.
1 Compress JavaScript code
When compressing JavaScript code, we need to parse the code into AST syntax tree first. This process is very computation-intensive. The commonly used plug-in is Webpack-u gli-fi – Parallel. Through Webpack-Ugli-fi parallel, we can assign the compression process of each resource to a separate process, so as to improve the overall compression efficiency. This plug-in is not inside Webpack and needs to be installed separately. The configuration method is also simple, as follows:
OS is the nodeJs module that provides some basic system operation functions
const os = require('os');
const UglifyJsParallelPlugin = require('webpack-uglify-parallel');
new UglifyJsParallelPlugin({
// Enable multiple processes workers: os.cpus().length, mangle: true. compressor: { // Ignore warnings warnings: false. / / open the console drop_console: true. / / open the debugger drop_debugger: true } }) Copy the code
2 Compress the CSS code
The ExtractTextPlugin and CSsnano are recommended for Webpack3. x, but webpack4. x has eliminated these two configuration items. For WebPack4, MiniCssExtractPlugin and OptimizeCSSAssetsPlugin are used. The specific configuration is as follows:
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{ test: /\.css$/. use: [ MiniCssExtractPlugin.loader, // Separate the CSS code 'css-loader'.]. }, ]. }, plugins: [ new MiniCssExtractPlugin({ filename: 'static/css/[name].[contenthash:8].css' // Extract the CSS storage directory }), new OptimizeCssAssetsPlugin() // Use OptimizeCssAssetsPlugin to compress CSS ] } Copy the code
3 Compressing images
Images are the largest static resource in a typical project, so image compression is very important. The imagemin-webpack-plugin is commonly used for image compression. The configuration is simple as follows:
const ImageminPlugin = require('imagemin-webpack-plugin').default;
module.exports = {
plugins: [
new ImageminPlugin({
pngquant: {
// Specify the compressed image quality quality: '95-100' } }) ] } Copy the code
Other optimizations will be published in another article…