19. 1. NoParse: Does not parse dependent libraries that are not needed to reduce packaging time

  1. $ mkdir webpack-optimize && cd webpack-optimize && yarn init -y
  2. The installation package:$ cnpm i webpack webpack-cli html-webpack-plugin @babel/core @babel/preset-env babel-loader @babel/preset-react webpack-dev-server -D
  3. webpack.config.js NoParse: /jquery/, // Does not parse dependent libraries in jquery
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'}, module: {noParse: /jquery/, //test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets:[
              '@babel/preset-env'.'@babel/preset-react'
            ]
          }
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'}})]Copy the code

20.IgnorePlugin: A plugin skipped while packaging

  1. Excloud and inclOUD are excludedinclude: path.resolve('src'),exclude: /node_modules/,
  2. Install package moment; Momentjs.com;
  3. webpack.config.js
let webpack = require('webpack'); Plugins: [new webpack.ignoreplugin (/\.\/locale/,/moment/), // not to reference locale package]Copy the code
  1. src/index.js
let moment = require('moment');
import 'moment/locale/zh-cn'; // Use a separate zh-CN package to reduce the size of the package moment.locale('zh-cn');
let time = moment().endOf('day').fromNow();
console.log(time);
Copy the code

21, 3. DllPlugin: dynamic link library

  1. Install the react react-dom package
  2. use
  • index.html
<div id="root"></div>
Copy the code
  • index.js
import React from 'react';
import { render } from 'react-dom';
render(<h1>jsx</h1>, window.root);
Copy the code
  • webpack.config.js
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let webpack = require('webpack');
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  devServer: {
    port: 3000,
    open: true, 
    contentBase: './dist'
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve('src'),
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env'.'@babel/preset-react'}}}]}, plugins: [new HtmlWebpackPlugin({template:'./src/index.html'
    }),
    new webpack.IgnorePlugin(/\.\/locale/, /moment/),
  ]
}
Copy the code
  1. Principle of separate file: By importing JS files, the library is exported to the dist directory through variables
  • Create a new file, webpack.config.test.js test.js
  • webpack.config.test.js
let path = require('path');
module.exports = {
  mode: 'development',
  entry: {
    test: './src/test.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'), 
    library: 'test'// Pass the variabletestGet the exported value vartest = 'kft'
    libraryTarget: 'var'// Default var, umd, commonjs... }}Copy the code
  • Test. Js:module.exports = 'kft'
  • NPX webpack –config webpack.config.test.js = ‘KFT’
  1. React and react-dom are introduced separately
  • New webpack. Config. React. Js
let path = require('path');
let webpack = require('webpack');
module.exports = {
  mode: 'development',
  entry: {
    react: ['react'.'react-dom']
  },
  output: {
    filename: '_dll_[name].js',
    path: path.resolve(__dirname, 'dist'),
    library: '_dll_[name]',
    // libraryTarget: 'commonjs'// default var, umd}, plugins: [new webpack.dllplugin ({name:'_dll_[name]',
      path: path.resolve(__dirname, 'dist'.'manifest.json')]}})Copy the code
  • Webpack. Config. Js added
let webpack = require('webpack');

  plugins: [
    new webpack.DllReferencePlugin({
      manifest: path.resolve(__dirname, 'dist'.'manifest.json') // Check if there is a separate library in manifest.json}),]Copy the code
  • Introduced in the SRC/index. HTML<script src="_dll_react.js"></script>*. React render(JSX,window.root) devServer port open contentBase ‘./dist webpack.config.react.js test.js module.exports = ‘kft’ webpack.config.react.js path exports entry test.js output filename ‘[name].js’ path dist library ab libraryTarget var react react-dom_dll_[name].js _dll_[name] plugins>.DLLPlugin() name path __dirname ‘dist’ ‘manifest.json’ webpack.config.js plugins> .DLLReferencePlugin manifest path.

22. 4. Happypack: Multi-threaded packaging

  1. The installation package happypack
  2. Assign threads when using the Loader
  • webpack.config.js
let Happypack = require('happypack');

  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve('src'),
        exclude: /node_modules/,
        use: 'Happypack/loader? id=js'
      },
      {
        test: /\.css$/,
        include: path.resolve('src'),
        exclude: /node_modules/,
        use: 'Happypack/loader? id=css'
      }
    ]
  },
  plugins: [
    
    new Happypack({
      id: 'js',
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [
            '@babel/preset-env'.'@babel/preset-react'
          ]
        }
      }]
    }),
    new Happypack({
      id: 'css',
      use: ['style-loader'.'css-loader'"})"Copy the code

5. Webpack optimization: Tree-shaking and scope hosting

  1. test.js
let sum = (a, b) => {
  return a + b + 'sum';
}
let minus = (a, b) => {
  return a - b + 'minus';
}
export default {
  sum, minus
}
Copy the code
  1. index.js
// Using import, packaging in production automatically removes unnecessary code, tree-shaking ES6 automatically removes unnecessary code // import calc from'./test'; / / the console. The log (calc. Sum (1, 2)); // In the production environment, the sum function is packaged, but the minus function is not packagedlet calc  = require('./test'); // console.log(calc.default.sum(1,2)); // In a production environment, both methods will be packagedlet a = 1;
let b = 2;
let c = 3;
let d = a + b + c;
console.log(d, '-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -'Console. log(6,"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -")
Copy the code

Decouple common code: Multi-page packaging decouple common code and third-party plug-ins

  1. + documents
    1. a.js console.log('a~~~~~~~');
    2. b.js console.log('b~~~~~~~');
    3. index.js/other.js import './a'; import './b'; import $ from 'jquery'; console.log($);
  2. webpack.config.js +
  entry: {
    index: './src/index.js',
    other: './src/other.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'}, optimization: {// common chunkplugins splitChunks: {// common chunkchunks: {// common chunkchunks: {// common chunkchunks: {// common chunkchunks: {//'initial', minSize: 0, minChunks: 2}, verdor: {priority: 1, //test: /node_modules/, // remove chunks from third-party modules:'initial',
          minSize: 0,
          minChunks: 2
        }
      }
    }
  },
Copy the code

7. Lazy loading

  1. The installation package:@babel/plugin-syntax-dynamic-import
  2. webpack.config.js +
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env'.'@babel/preset-react'
            ],
            plugins: [
              '@babel/plugin-syntax-dynamic-import']}}},Copy the code
  1. src/index.js
let button = document.createElement('button');
button.innerHTML = 'click';
button.addEventListener('click'.function(){// es6 draft syntax, jSONp implementation dynamic load file import('./source.js').then((data)=>{
    console.log(data.default);
  })
})
document.body.appendChild(button);
Copy the code
  1. src/source.js
export default 'kft';
Copy the code

26. 8. Hot update: incremental update without refreshing the page

  1. webpack.config.js +
  devServer: {
    hot: true,}, plugins: [new webpack NamedModulesPlugin (), / / print update module new webpack HotModuleReplacementPlugin () / / hot update plugins]Copy the code
  1. SRC /index.js uses hot updates
// import str from './source';
if (module.hot) {
  module.hot.accept('./source', () = > {let str = require('./source');
    console.log(str)
  })
}
Copy the code

webpack.config.js

let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let webpack = require('webpack');
// let Happypack = require('happypack'); Module. exports = {optimization: {commonChunkPlugins splitChunks: {// commonChunkPlugins: {// cacheGroups: {// cache group common: {// common module chunks:'initial',
          minSize: 0,
          minChunks: 2
        },
        verdor: {
          priority: 1,
          test: /node_modules/, // remove chunks from third-party modules:'initial',
          minSize: 0,
          minChunks: 2
        }
      }
    }
  },
  mode: 'production',
  entry: {
    index: './src/index.js',
  },
  devServer: {
    // hot: truePort: 3000, open:true,
    contentBase: './dist'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'}, module: {// noParse: /jquery/, //test: /\.js$/,
        include: path.resolve('src'),
        exclude: /node_modules/,
        // use: 'Happypack/loader? id=js'Use: {loader:'babel-loader',
          options: {
            presets: [
              '@babel/preset-env'.'@babel/preset-react'
            ],
            plugins: [
              '@babel/plugin-syntax-dynamic-import'}}}, {test: /\.css$/,
        include: path.resolve('src'),
        exclude: /node_modules/,
        // use: 'Happypack/loader? id=css'
        use: ['style-loader'.'css-loader']}}], plugins: [/ / dynamic link library / / new webpack DllReferencePlugin ({/ / manifest: path. Resolve (__dirname,'dist'.'manifest.json')
    // }),

    new HtmlWebpackPlugin({
      template: './src/index.html'}), // new webpack.NamedModulesPlugin(), / / print the module/update/new webpack HotModuleReplacementPlugin () / / hot plug-in/update/new webpack. IgnorePlugin (/ \ \ / locale /, / the moment /), // new Happypack({// id:) {// new Happypack({// id:); // new Happypack({// id:);'js',
    //   use: [{
    //     loader: 'babel-loader',
    //     options: {
    //       presets: [
    //         '@babel/preset-env', / /'@babel/preset-react'
    //       ]
    //     }
    //   }]
    // }),
    // new Happypack({
    //   id: 'css',
    //   use: ['style-loader'.'css-loader'[//})]}Copy the code

package.json

{
  "name": "webpack-optimize"."version": "1.0.0"."description": ""."main": "webpack.config.js"."scripts": {
    "build": "webpack --config webpack.config.js"."dev": "webpack-dev-server"
  },
  "keywords": []."author": ""."license": "ISC"."devDependencies": {
    "@babel/core": "^ 7.4.5"."@babel/plugin-syntax-dynamic-import": "^ 7.2.0"."@babel/preset-env": "^ 7.4.5"."@babel/preset-react": "^ 7.0.0." "."babel-loader": "^ 8.0.6"."css-loader": "^ 3.0.0"."happypack": "^ 5.0.1." "."html-webpack-plugin": "^ 3.2.0"."react": "^ 16.8.6"."react-dom": "^ 16.8.6"."style-loader": "^ 0.23.1"."webpack": "^ 4.35.2"."webpack-cli": "^ 3.3.5." "."webpack-dev-server": "^ 3.7.2." "
  },
  "dependencies": {
    "jquery": "^ 3.4.1 track"."moment": "^ 2.24.0"}}Copy the code