What is HTTP compression?


Current compression format


Webpack compresses files

  • npm install compression-webpack-plugin -D


Compression of code in HTML files


package.json

{
  "name": "webpack_devserver"."sideEffects": false."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "build": "webpack --config ./config/webpack.common.js --env production"."serve": "webpack serve --config ./config/webpack.common.js --env development"
  },
  "author": ""."license": "ISC"."devDependencies": {
    "@babel/core": "^ 7.12.17"."@babel/preset-env": "^ 7.12.17"."@babel/preset-react": "^ 7.12.13"."@pmmmwh/react-refresh-webpack-plugin": "^ 0.4.3." "."babel-loader": "^ 8.2.2"."clean-webpack-plugin": "^ 3.0.0"."compression-webpack-plugin": "^ 7.1.2." "."css-loader": "^ 5.0.2"."css-minimizer-webpack-plugin": "^ 1.2.0"."html-webpack-plugin": "^ 5.2.0." "."mini-css-extract-plugin": "^ 1.3.9"."purgecss-webpack-plugin": "^ 4.0.2." "."react-dev-utils": "^ 11.0.3"."react-refresh": "^ 0.9.0"."style-loader": "^ 2.0.0." "."vue-loader": "^ 15.9.6"."vue-template-compiler": "^ 2.6.12." "."webpack": "^ 5.23.0"."webpack-cli": "^ 4.5.0." "."webpack-dev-server": "^ 3.11.2"."webpack-merge": "^ 5.7.3." "
  },
  "dependencies": {
    "axios": "^ 0.21.1"."coderwhy_utils": "^ 1.0.0"."dayjs": "^ 1.10.4"."express": "^ 4.17.1"."lodash": "^ 4.17.21"."react": "^ 17.0.1"."react-dom": "^ 17.0.1"."react-router-dom": "^ 5.2.0." "."terser": "^ 5.6.0"."vue": "^ 2.6.12." "."webpack-dev-middleware": "^ 4.1.0." "}}Copy the code

webpack.common.js

const resolveApp = require("./paths");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');

const { merge } = require("webpack-merge");

const prodConfig = require("./webpack.prod");
const devConfig = require("./webpack.dev");

const commonConfig = (isProduction) = > {
  return {
    entry: {
      main: "./src/main.js".// index: "./src/index.js"
    },
    output: {
      path: resolveApp("./build"),
      filename: "js/[name].[chunkhash:6].bundle.js".chunkFilename: "js/[name].[contenthash:6].chunk.js".publicPath: ""
    },
    resolve: {
      extensions: [".wasm".".mjs".".js".".json".".jsx".".ts".".vue"].alias: {
        "@": resolveApp("./src"),
        pages: resolveApp("./src/pages"),}},optimization: {
      // Perform compression operations on the code
      // use natural numbers (not recommended),
      // named: use the directory where the package resides as name(recommended in development environments)
      // Deterministic: id generation. Ids generated for the same file are unchanged
      // chunkIds: "deterministic",
      splitChunks: {
        // async asynchronous import
        // Initial Synchronized import
        // all Asynchronous/synchronous import
        chunks: "all".// Minimum size: If the package is split, the minimum size of the package is minSize
        minSize: 20000.// Divide a package larger than maxSize into a package larger than minSize
        maxSize: 20000.// minChunks represent imported packages that are imported at least a few times
        minChunks: 1.cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            filename: "js/[id]_vendors.js".// name: "vendor-chunks.js",
            priority: -10
          },
          // bar: {
          // test: /bar_/,
          // filename: "[id]_bar.js"
          // }
          default: {
            minChunks: 2.filename: "common_[id].js".priority: -20}}},// true/multiple
      // single
      // object: name
      runtimeChunk: {
        name: 'runtime'}},module: {
      rules: [{test: /\.jsx? $/i,
          use: "babel-loader"}, {test: /\.vue$/i,
          use: "vue-loader"}, {test: /\.css/i.// style-lodader -> development
          use: [
            isProduction ? MiniCssExtractPlugin.loader : "style-loader"."css-loader"].sideEffects: true // react scaffolding},],},plugins: [
      new HtmlWebpackPlugin({
        template: "./index.html".// inject: "body"
        cache: true.// If no changes have been made to the file, the previous cache is used
        minify: isProduction ? {
          removeComments: false.// Whether to remove the comment
          removeRedundantAttributes: false.// Whether to remove unnecessary attributes
          removeEmptyAttributes: true.// Whether to remove some empty attributes
          collapseWhitespace: false.// Whether to fold Spaces
          removeStyleLinkTypeAttributes: true.minifyCSS: true.// Whether to compress the CSS
           // whether to compress js
          minifyJS: {
            mangle: {
              toplevel: true}}} :false
      }),
      new VueLoaderPlugin(),
      // When a variable is not found in the code, we will automatically import the corresponding library through ProvidePlugin
      // new webpack.ProvidePlugin({
      // axios: "axios",
      // get: ["axios", "get"]
      // })]}; }module.exports = function (env) {
  const isProduction = env.production;
  process.env.NODE_ENV = isProduction ? "production" : "development";

  const config = isProduction ? prodConfig : devConfig;
  const mergeConfig = merge(commonConfig(isProduction), config);

  return mergeConfig;
};

Copy the code

webpack.prod.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const PurgeCssPlugin = require('purgecss-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const glob = require('glob');

const resolveApp = require('./paths');

const isProduction = true;

module.exports = {
  mode: "production".devtool: "source-map".externals: {
    lodash: "_".dayjs: "dayjs"
  },
  optimization: {
    UsedExports: The purpose is to indicate which functions are unused
    usedExports: true.// production
    minimize: true.minimizer: [
      // Remove unused functions from our code by Terser
      new TerserPlugin({
        parallel: true.extractComments: false.terserOptions: {
          compress: {
            arguments: false.dead_code: true
          },
          mangle: true.toplevel: true.keep_classnames: true.keep_fnames: true}}})],plugins: [
    // Build the environment
    new CleanWebpackPlugin({}),
    new MiniCssExtractPlugin({
      filename: "css/[name].[contenthash:6].css"
    }),
    new CssMinimizerPlugin(),
    new webpack.optimize.ModuleConcatenationPlugin(),
    // new PurgeCssPlugin({
    // paths: glob.sync(`${resolveApp("./src")}/**/*`, {nodir: true}),
    // safelist: function() {
    // return {
    // standard: ["body", "html"]
    / /}
    / /}
    // }),
    new CompressionPlugin({
      test: /\.(css|js)$/i,
      threshold: 0.// Set the size of the file to start compression
      minRatio: 0.8.// Minimum compression ratio
      algorithm: "gzip"./ / algorithm
      // exclude
      // include
    }),
    new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime.*\.js/,])]}Copy the code

webpack.dev.js

const resolveApp = require('./paths');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

const isProduction = false;

console.log("Load devConfig config file");

module.exports = {
  mode: "development".devServer: {
    hot: true.hotOnly: true.compress: true.contentBase: resolveApp("./why"),
    watchContentBase: true.proxy: {
      "/why": {
        target: "http://localhost:8888".pathRewrite: {
          "^/why": ""
        },
        secure: false.changeOrigin: true}},historyApiFallback: {
      rewrites: [{from: /abc/, to: "/index.html"}}},plugins: [
    // Development environment
    new ReactRefreshWebpackPlugin(),
  ]
}
Copy the code