Webpack core module

  • Mode environment configuration, production, development, none three values, default production
  • Entry Packages the entry file
  • Output Packages export files
  • Loader file parsing
  • Plugins plug-in configuration
module.exports = {
  mode: 'production'                   // Environment configuration, production, development, none, default production
  entry: './src/index.js'.// Package the entry file
  output: {                            // Package export files
    filename: '[name]_[hash].js'.path: path.join(__dirname, './dist')},module: {                            // File loader configuration
    rules: [{test: /\.js$/,
        loader: 'babel-loader'}},plugins: []                         // Plug-in configuration
}
Copy the code

loader example

js | jsx

npm install babel-loader @babel/core @babel/preset-env @babel/preset-react –save-dev

module.exports = {
  module: {
    rules: [{test: /\.(js|jsx)$/,
        options: {
          loader: "babel-loader".presets: [
            "@babel/preset-env".// es6+ => es5
            "@babel/preset-react".// jsx],},},],},};Copy the code

css | less

npm install style-loader css-loader less-loadr less –save-dev

module.exports = {
  module: {
    rules: [{test: /\.less$/,
        use: ["style-loader"."css-loader"].// loader executes from right to left
      },
      {
        test: /\.less$/,
        use: ["style-loader"."css-loader"."less-loader"].// loader executes from right to left},],}};Copy the code

watch

Principle: Polling determines whether the last edit time of a file has changed. If a file has changed, it will not tell listeners immediately. Instead, it will cache the file and wait for the aggregateTimeout to run

There are two Settings:

1, NPM scripts with –watch parameter

"watch" : "webpack --watch"
Copy the code

2. Webpack configuration

module.exports = {
  watch: true.// watch sets this parameter to true
  watchOptions: {
    // It defaults to null and does not listen for files
    ignored: /node_modules/.// Wait 300ms for the change to be executed
    aggregateTimeout: 300.// Polls listening files. Default is 1000 polls per second
    poll: 1000,}};Copy the code

Hot update HMR

Hot update: with webpack-dev-server, WDS does not refresh the browser, does not output files, but puts them in memory; Using webpack HotModuleRepleacementPlugin refresh the browser plugin

  1. Webpack configuration
const webpack = require("webpack");

module.exports = {
  plugins: [new webpack.HotModuleRepleacementPlugin()],
};
Copy the code
  1. NPM scripts to configure

webpack 4+

// package.json
{
  "scripts": {
    "dev": "webpack-dev-server --open --mode=development"}}Copy the code

webpack 5+

// package.json
{
  "scripts": {
    "dev": "webpack server --open --mode=development"}}Copy the code

Principle of thermal renewal

Hot updates have two phases:

  1. Startup phase
  2. File changes update phase
  • Webpack Compile: Compile the JS files into the corresponding Bundle files
  • HMR Server: outputs hot updated files to the HMR Runtime
  • Bundle Server: a service that provides file access in the browser
  • HMR Runtime: will be injected into the browser to update the file changes

File fingerprint

Hash, chunkhash, contenthash

  1. Hash: Is associated with the overall project build, and changes as the project-related files change

  2. Chunkhash: Related to the Webpack entry entr entry file, different entries will generate different chunkhash values

  3. Contenthash: Depending on the content of the document, only the document changes

Js file fingerprint setting

const path = require("path");

module.exports = {
  output: {
    filename: "[name]_[chunkhash:8].js".path: path.join(__dirname, "./dist"),}};Copy the code

Set the fingerprint of the CSS

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  module: {
    rules: [{test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],}, {test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"."less-loader"],},],},plugins: [
    new MiniCssExtractPlugin({
      filename: `[name]_[contenthash:8].css`,})]};Copy the code

Image and file fingerprint Settings

module.exports = {
  module: {
    rules: [{test: /\.(png|jpeg|jpg|gif)$/,
        use: {
          loader: "file-loader".options: {
            name: "[name]_[hash:8].[ext]",},},},],},};Copy the code

To set file-loade’s name, use [hash]

Meaning of placeholder for the file

Placeholder name meaning
[ext] File name extension
[name] The file name
[path] File relative path
[folder] The folder where the file resides
[contenthash] File content hash, generated by MD5 by default
[hash] File content hash, generated by MD5 by default

HTML, CSS, javascript code compression

html

npm install html-webpack-plugin –save-dev

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

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html".filename: "index.html",})]};Copy the code

css

4 webpack + version

npm install optimize-css-assets-webpack-plugin cssnano –save-dev

const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const cssnano = require('cssnano');

module.exports = {
  plugins: [
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.css$/,
      cssProcessor: cssnano,
    }),
  ];
}
Copy the code

Webpack 5. + version

npm install css-minimizer-webpack-plugin –save-dev

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

module.exports = {
  optimization: {
    minimize: true.minimizer: [
      new CssMinimizerPlugin({
        parallel: true.// Enable/disable concurrent execution of multiple processes})],}};Copy the code

javascript

const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  optimization: {
    minimize: true.minimizer: [
      new TerserPlugin({
        parallel: true.// Enable/disable concurrent execution of multiple processes})],}};Copy the code

Mode: production enables JS compression

Clear build directory

npm install clean-webpack-plugin –save-dev

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

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

Webpack 5+ uses output.clean Settings

module.exports = {
  output: {
    clean: true,}};Copy the code

Css3 automatically adds the vendor prefix

npm install postcss-loader autoprefixer -save-dev

module.exports = {
  module: {
    rules: [{test: /\.css$/,
        use: [
          "style-loader"."css-loader",
          {
            loader: "postcss-loader".options: {
              postcssOptions: {
                plugins: [["autoprefixer"],},},},],},},};Copy the code

Extract common resources

module.exports = {
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendors: {
          name: "vendors".test: /(react|teact-dom)/,
          chunks: "all",},},},},};Copy the code

Tree Shaking Principles and Analysis

Code that analyzes code for the following situations will be shaken by Tree

  1. Code will not be executed, not reachable
  2. The results of code execution are not used
  3. Code only affects dead variables (read only, not written)

Principle Using es6 module features:

  1. Can only occur as a top-level statement
  2. The module name for import must be a string constant
  3. Import binding is immutable

Code erase: The Ugify phase removes useless code

Scope principle and analysis

Analyze that each module will be wrapped after webpack construction, increasing the code volume after construction; The code is built with lots of closures, function scopes are created at run time, and memory overhead becomes

The principle is built by placing module references in a function scope in reference order, and then appropriately renaming to prevent variable name conflicts

Scope collieries can reduce function declaration code and memory development

Webpack version 4 + default has been integrated, set mode: production, webpack 3 version Settings: new webpack. Optimize. ModuleConcatenationPlugin ()

const webpack = require("webpack");

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

Code splitting and dynamic import

npm install @babel/plugin-syntax-dynamic-import –save-dev

// .babbelrc
{
  "presets": []."plugins": [
    "@babel/plugin-syntax-dynamic-import"
  ];
}
Copy the code

Build speed and volume optimization strategies

Build speed

Analyze the loader and Plugin time

npm install speed-measure-webpack-plugin –save-dev

const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  // webpackConfig
});
Copy the code

Optimization strategy

  1. Multi-process, multi-instance build

recommendation

npm install thread-loader –save-dev

module.exports = {
  module: {
    rules: [{test: /\.js$/,
        use: [
          {
            loader: "thread-loader".options: [
              workders: true],},'babel-loader'],},],},};Copy the code

alternative

npm install happypack –save-dev

const Happypack = require("happypack");

module.exports = {
  module: {
    rules: [{test: /\.js$/,
        use: ["happypack/loader"],},],},plugins: [
    new Happypack({
      loaders: ["babel-loader"],}),]};Copy the code
  1. precompiled

Use the Dllplugin to separate the base package

const webpack = require('path');
const path = require('path');

module.exports = {
  entry: {
      library: [
          'react'.'react-dom' // Separate base packages]},output: {
      filename: '[name]_[chunkhash:8].dll.js'.path: path.join(__dirname, './library'),
      library: '[name]'
  },
  plugins: [
    new new webpackDllplugin({
       name: '[name]'.path: path.join(__dirname, 'manifest.json')]}})Copy the code

DllReferencePlugin is introduced into the manifest. Json

module.exports = {
  plugins: [
    new webpack.DllReferencePlugin({
      manifest: require(/* Precompile the base package path */),})]};Copy the code

The cache

  1. Babel cache Babel – loader? cacheDirectory=true
  2. Code compression cache zerser-Webpack-plguin
  3. Module cache hard-source-webpack-plugin

babel-loader

module.exports = {
  module: {
    rules: [{test: /\.js$/,
        user: [{
          loader: 'babel-loader'.options: {
            cacheDirectory: true}}]}}Copy the code

terser-webpack-plugin

hard-source-webpack-plugin

Narrow your Build goals

Build the volume

Packet size analysis

npm install webpack-bundle-analyzer –save-dev

const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");

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

Optimization strategy

  1. Multi-process parallel compression code

npm install terser-webpack-plugin css-minimizer-webpack-plugin –save-dev

module.exports = {
  optimization: {
    minimize: true.minimizer: [
      new CssMinimizerPlugin({
        parallel: true.// Enable multi-process parallel compression code
      }),
      new TerserPlugin({
        parallel: true.// Enable/disable multi-process parallel compression code})],}};Copy the code