Front-end construction and compilation code, compression code is also very important, compressed code volume reduced, fast transmission speed, thereby improving the speed of web pages and reduce network transmission traffic. In addition, it also has the effect of confusing the source code, because the readability of the code after compression is very poor, even if others download the code of the web page, but also greatly increased the difficulty of code analysis and transformation.

Compression JS

At present, the most mature JavaScript code compression tool is UglifyJS, which will analyze the syntax tree of JavaScript code and understand the meaning of the code, so as to achieve optimization such as removing invalid code, removing log output code, shortening variable names, etc.

In WebPack V4, uglifyjs-webpack-plugin is integrated into production mode by default. Therefore, the default packaged JS file is compressed. If you need more customization, you can also configure uglifyjs-webpack-plugin.

First, install uglifyjs-webpack-plugin:

npm install uglifyjs-webpack-plugin --save-dev
Copy the code

Then, add it to your WebPack configuration:

const UglifyJsPlugin = require("uglifyjs-webpack-plugin");

module.exports = {
  optimization: {
    minimizer: [new UglifyJsPlugin()],
  },
};
Copy the code

Configurable items of uglifyjs-webpack-plugin:

  • Test: tests the matching file. Default: /\.js(\? . *)? $/i

    module.exports = {
      optimization: {
        minimizer: [
          new UglifyJsPlugin({
            test: /\.js(\? . *)? $/i,}),],},};Copy the code
  • Include: The file to be processed.

  • Exclude: indicates the file that is not to be processed.

  • ChunkFilter: Determines which chunks can be compressed (all chunks are compressed by default). The return value true is compressed, false is not compressed.

    module.exports = {
      optimization: {
        minimizer: [
          new UglifyJsPlugin({
            chunkFilter: (chunk) = > {
              // the 'vendor' block is not compressed
              if (chunk.name === "vendor") {
                return false;
              }
    
              return true; },}),],},};Copy the code
  • Cache: starts the file cache, default is false, default cache directory path: node_modules/. Cache /uglifyjs-webpack-plugin

  • Parallel: Use multiple processes to run parallel to improve build speed. The default value is false and this function is recommended.

  • SourceMap: Uses source mapping to map error message locations to modules (which slows compilation). Default is false.

  • UglifyOptions: UglifyJS compression configuration options.

Compress CSS

CSS code can also be compressed like JS. At present, the more mature and reliable CSS compression tool is CSsnano. Cssnano can understand the meaning of CSS code, not just delete Spaces, for example:

Copy the code

For webpack v5 or higher, the official recommended CssMinimizerWebpackPlugin, the plug-in is to use cssnano optimization and compress CSS, support caching and concurrent mode.

First, we need to install the CSS-Minimizer-webpack-plugin:

npm install css-minimizer-webpack-plugin --save-dev
Copy the code

Then add the plug-in to the WebPack configuration:

const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  // ...
  optimization: {
    minimizer: [
      // In webpack@5, you can use '... 'syntax to extend existing minimizer (i.e.,' terser-webpack-plugin '), uncomment the next line
      `... `.new CssMinimizerPlugin(),
    ],
  },
};
Copy the code

Compressed HTML

HtmlWebpackPlugin can not only help us to simplify the creation of HTML files, but also compress HTML files.

First, you need to install HtmlWebpackPlugin:

npm install --save-dev html-webpack-plugin
Copy the code

Add to the WebPack configuration file:

// webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  plugins: [new HtmlWebpackPlugin()],
};
Copy the code

If no configuration is added, a default index.html file is generated and all chunks and compression are automatically injected.

You can also customize configuration parameters. The following are common parameters:

  • template: The path to the template, which is found by defaultsrc/index.ejsWhether there is.
  • filename: Specifies the name of the output fileindex.html.
  • inject: Indicates whether to inject resources into the template. The default value istrue.
  • minify: Compression parameter. In production mode (production), the default istrue; Otherwise, the default value isfalse.

If minify is true, the generated HTML is compressed using htML-minifier-terser with the following options:

{
  collapseWhitespace: true.keepClosingSlash: true.removeComments: true.removeRedundantAttributes: true.removeScriptTypeAttributes: true.removeStyleLinkTypeAttributes: true.useShortDoctype: true
}
Copy the code

Webpack series

  • preface
  • Extremely brief introduction
  • The core concept
  • Parse the file
  • File listening and hot update
  • File fingerprint Policy
  • Code compression
  • CSS enhancement: Autoprefixer
  • Multi-page Application Packaging Solution (MPA)