See what versions are available:

npm view compression-webpack-plugin versions
Copy the code

Install the old version:

yarn add compression-webpack-plugin@5
Copy the code

Modify the webpack.config.js file:

const CompressionPlugin = require('compression-webpack-plugin')
const isGzip = process.env.GENERATE_GZIP_FILE === 'true'
plugins: [
  // ...
  isEnvProduction && isGzip && new CompressionPlugin({
    filename: '[path].gz[query]'.algorithm: 'gzip'.test: /\.js$|\.css$/,
    threshold: 10240.// Compress data over 10K
    minRatio: 0.8.// Only resources whose compression ratio is less than this value will be processed})]Copy the code

 

The node open gzip:www.npmjs.com/package/com…

$ npm install compression
Copy the code
var compression = require('compression')
var express = require('express')
 
var app = express()
app.use(compression({ filter: shouldCompress }))
 
function shouldCompress (req, res) {
  if (req.headers['x-no-compression']) {
    // don't compress responses with this request header
    return false
  }
 
  // fallback to standard filter function
  return compression.filter(req, res)
}
Copy the code

 

 

 

 

The basic principle of

  1. The browser requests resource files automatically with an accept-encoding header that tells the server what Encoding is supported

  2. Server configuration enable gzip option:

    Content-encoding: gzip If the request contains gzip, return the resource file in response to the request (content-encoding: gzip).

  3. The browser receives the response and looks to see if the request header contains Content-Encoding :gzip, and if so, decompresses the returned resource file and then parses the rendering

Pay attention to the point

  • For lower version browser compatibility, the server can set some ignore rules to ignore the browser
  • Media files don’t need to be opened: images, music, AND videos are mostly compressed, HTML,CSS, AND JAVARSCRIPT
  • CPU load: CPU used to compress files (the server needs to compress files and the browser decompresses files)

Webpack optimization

  • If you use Webpack, you can use the CompressionWebpackPlugin to Gzip the files ahead of time
  • In this way, the server directly reads. Gz files with the same name as the source file, and does not compress them actively, reducing the CPU load and optimizing the server performance