Writing is not easy, without the permission of the author forbid to reprint in any form! If you think the article is good, welcome to follow, like and share!

HTTP compression

  • HTTP compression is a built-in way to improve transmission speed and bandwidth utilization between servers and clients.

  • What is the process of HTTP compression?

    • Step 1 :HTTP data is compressed before the server sends it. (This can be done in Webpack)
    • Step 2: When a compatible browser sends a request to the server, it tells the server which compression formats it supports.
    • Step 3: The server directly returns the corresponding compressed file in the compression format supported by the browser, and informs the browser in the response header;

Compressed format

  1. Compress – Method of the UNIX compress program (not recommended for most applications for historical reasons, should use gZIP or

    deflate);

  2. Deflate — Compression based on the Deflate algorithm (defined in RFC 1951), encapsulated using the Zlib data format;

  3. Gzip – GNU ZIP format (defined in RFC 1952), is currently used more widely compression algorithm;

  4. Br – a new open source compression algorithm designed for encoding HTTP content;

Webpack compresses files

Use the CompressionPlugin to compress the file

  • The installation

    • npm install compression-webpack-plugin
  • webpack.prod.js

    • Threshold: Compress only files whose values are larger than x
    • MinRatio: indicates the minimum compression ratio. If the value is smaller than this, no compression is performed
    • Test: Compress only the files that match the re
    • Alogorithm: Compression algorithm
const CompressionPlugin = require("compression-webpack-plugin")

plugins: [new  CompressionPlugin({
        threshold: 0.minRatio:0.6.test:/\.(css|js)/i,
        algorithm:"gzip"})]Copy the code

Compression of code in HTML files

  • The HtmlWebpackPlugin plugin was used to generate the HTML template. In fact, it has several other configurations:

  • Inject: sets the location where the packaged resource is inserted

    • True, false, body, and head
  • Cache: Set to true to generate new files only when they change (also true by default)

  • Minify: A plugin html-minifier-terser is used by default

  • webpack.prod.js

plugins: [
    new HtmlWebpackPlugin({
        title: "LeBronChao Webpack".template: "./src/index.html".inject:"body".cache:true.minify: isProduction ? {
            removeComments: true.// Whether to delete comments
            removeRedundantAttributes:true.// Whether to remove redundant (default) attributes
            removeEmptyAttributes:true.// Whether to delete the null attribute
            collapseWhitespace:false.// Fold the space
            removeStyleLinkTypeAttributes:true.// Link type="text/ CSS"
            minifyCSS:true.// Whether to compress the CSS inside the style tag
            minifyJS: {// To compress JS options, see Terser configuration
                mangle: {toplevel: true}}} :false}),]Copy the code

InlineChunkHtmlPlugin

  • There is also a plugin that helps to inline some chunk-out modules into HTML:

    • The runtime code, for example, is small but must be loaded.
    • So you can inline it directly into HTML;
  • This plugin is implemented in React-dev-utils, so we can install it:

    • npm i react-dev-utils
  • Configuration (inline Runtime file) in the production plugins:

    • webpack.prod.js
    • Parameter one is HtmlWebpackPlugin
    • Parameter 2 is a regular matching expression
const InlieChunkHtmlPlugin = require("react-dev-utils/InlineChunkHtmlPlugin")

plugins: [new InlieChunkHtmlPlugin(HtmlWebpackPlugin,[/runtime.+\.js/]]Copy the code

Terser

  • What is a Terser?

    • Terser is a JavaScript toolset that interprets Parser, Mangler, and Compressor.
    • In the early days, uglify-js was used to compress and uglify JavaScript code, but it is no longer maintained and ES6+ syntax is not supported.
    • Terser comes from the Uglify-es fork and retains most of its original API and ADAPTS to Uglify-es, uglify-js@3, etc. In other words, Terser can help compress, ugly code, and make our bundle smaller.
  • Because Terser is a stand-alone tool, it can be installed separately:

    • npm i terser -g
  • Terser can be used on the command line

    • Because they have a lot of Compress options and Mangle options
    • See the document for details
      • Github.com/terser/ters…
      • Github.com/terser/ters…

Configure Terser in Webpack

  • First, you need to turn on minimize to compress the code (it’s already turned on in production mode by default)

  • Second, you can create a TerserPlugin in minimizer:

    • ExtractComments: The default value is true, indicating that the comments are extracted into a separate file;
      • During development, when you don’t want to keep the comment, you can set it to false;
    • Parallel: improves build speed by running multiple processes concurrently. The default value is true. The default number of concurrent runs is os.cpus().length-1;
      • You can also set your own number, but use the default;
    • TerserOptions: Sets the configuration related to terser
      • Compress: sets compression related options.
      • Mangle: Set uglification related options. This can be set to true.
      • Toplevel: Whether the underlying variable is transformed;
      • Keep_classnames: reserved classnames;

CSS compression

  • Another compression of code is CSS:

    • CSS compression usually removes unnecessary whitespace, because it is difficult to modify selectors, property names, values, etc.
    • To compress CSS, we can use another plugin :css-minimizer-webpack-plugin;
    • The csS-Minimizer-Webpack-plugin uses the CSSNano tool to optimize and compress CSS(or can be used alone).
  • Installing CSS – minimizer – webpack – the plugin:

    • npm i css-minimizer-webpack-plugin
  • Configure in optimization.minimizer

Configuration of the sample

  • webpack.prod.js
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const isProduction = true
const TerserPlugin = require("terser-webpack-plugin")
const CssMiniMizerPlugin = require("css-minimizer-webpack-plugin")
module.exports = {
    mode: "production".optimization: {
        chunkIds: "deterministic".minimize:true.minimizer: [new TerserPlugin({
                extractComments:true.parallel:true.terserOptions: {compress:true.mangle:true.toplevel:false.keep_classnames:false}}),new CssMiniMizerPlugin({
                parallel:true}})],plugins: [
        new CleanWebpackPlugin(),
        new CopyWebpackPlugin({
            patterns: [{from: "public".// Do not write, default to output
                    to: "".globOptions: {
                        ignore: ["**/index.html"."**/.DS_Store"."**/abc.txt"],},},],})]}Copy the code

  • Nuggets: LeBron on the front end

  • Zhihu: LeBron on the front end

  • Keep sharing technical blog posts, follow wechat public account 👉🏻 front-end LeBron