1.tree shaking

1. Code not used in context

2. All code must be based on ES6 import and export

3. Mode =’production ‘tree-shaking

new TerserPlugin(/ *... * /), // This plugin is tree-shaking
Copy the code

The principle is that webpack comments uncommented code and TerserPlugin removes those comments

Disadvantages: We may modify the global scope, such as modifying properties and methods on window. This is not shown in export. If shake drops, the code will be broken

Sideeffects tells webpack what sideeffects can’t be removed (file list)

Because CSS is usually not export /import, but you use js files that you know affect the global scope

4. Babel sets modules: false

module.exports = {
    presets: [['@babel/preset-env'.// A collection of Babel plug-ins
            {
                modules: false./ /! Do not transform ES6 into low-level modular syntax to prevent tree-shaking
                "targets": {
                    "browsers": ["0.25%" >]},"useBuiltIns": "usage"."bugfixes": true}].'@babel/preset-react'].plugins: [
        '@babel/plugin-proposal-class-properties'."@babel/plugin-transform-runtime"]};Copy the code

2. Js compressed

Terser-webpack-plugin is better than uglifyjs and is available in production mode

3. Scope enhancement

Without scope promotion enabled, we import the dependent module and give it a name and then call the dependent module

Webpack will analyze the dependency analysis and merge the dependency file into this file, taking this value directly

Production mode has scope promotion enabled automatically

4. Babel7 configuration

1. Configure polyfill to introduce Babel/Polyfill. This package is compatible with all apis of the browser, such as include WeakMap, but we don’t need so much compatibility

"useBuiltIns": "usage".Copy the code

Every time we declare a class, we create a helper function _classCallcheck that implements some of the class’s inheritance methods, This will save a lot of code if all of our classes share this function. “@babel/plugin-transform-runtime”, on

"@babel/plugin-transform-runtime".Copy the code

3. Select by browser the more supported the more browser code

5. Webpack packaging speed optimization

1.noparse:

Some libraries do not use recursive parsing, such as external large libraries (because they do not Import other libraries). Ignored libraries cannot be modularized and cannot have Import require define such as loadsh/jquery

module.exports = {
  / /...
  module: {
    noParse: /jquery|lodash/,}};Copy the code

2.dllplugin

We extract a library as a reference to a dynamically linked library that doesn’t need to be built over and over again each time we build and use the previous reference to avoid having to build over and over a library that doesn’t change when we package it like react React -dom

The webpack.dll.config.js function generates DLL files

const path = require("path");
const webpack = require("webpack");
module.exports = {
    mode: "production".entry: {
        react: ["react"."react-dom"],},output: {
        filename: "[name].dll.js".path: path.resolve(__dirname, "dll"),
        library: "[name]"
    },
    plugins: [
        new webpack.DllPlugin({
            name: "[name]".path: path.resolve(__dirname, "dll/[name].manifest.json")]}});Copy the code

Webpack.config. js uses the DLL file to use the corresponding descriptor file

 
      new DllReferencePlugin({
            manifest: require(`${__dirname}/dll/react.manifest.json`)})Copy the code

Application scenario: The development environment used more

The autodllPlugin follows

module.exports = {
  / /...
  plugins: [
        // Step 2: Configure the file to be packaged as a DLL
        new AutoDllPlugin({
            inject: true.// Set this object to true to insert DLL bundles into index.html
            filename: '[name].dll.js'.context: path.resolve(__dirname, '.. / '), // The AutoDllPlugin context must be the same directory as package.json, otherwise the link will fail
            entry: {
                react: [
                    'react'.'react-dom']}})]}Copy the code

The dllplugin is replaced directly with HardSourceWebpackPlugin later because it works better

6. Build environment optimization

1. Code splitting

 entry: {
        app: './src/index.jsx'.test:'./src/test.js'
    },
Copy the code

The two entry Webpack will recursively analyze the dependency relationship of export and Import from the beginning of the two entries respectively to form two bundles

Splitchunks extract common code and separate business code from common code. Partial code changes only change the corresponding bundle

optimization: {
        splitChunks: {
            cacheGroups: {/ / group
                vendor: {
                    name: 'vendor'.test: /[\\/]node_modules[\\/]/.// Extract third-party libraries as separate bundles
                    minSize: 0.minChunks: 1.priority: 10.chunks: 'initial'
                },
                common: {
                    name: 'common'.// The extract business common code name is common
                    test: /[\\/]src[\\/]/,
                    chunks: 'all'.// All consider both static and dynamic instalments like components introduced in Suspense async initial
                    minSize: 0.minChunks: 2// Common chunks are packaged only when chunks are introduced together twice}}}},Copy the code

Synchronous loading up here and asynchronous loading down here

7. Webpack-based resource compression

minification

  new UglifyJsPlugin(/ *... * /),//js
        new MiniCssExtractPlugin({// Extract a CSS file from the js file
            filename: '[name].[contenthash].css'.chunkFilename: '[id].[contenthash:8].css',}).new OptimizeCssAssetsPlugin({
            cssProcessorPluginOptions: {
                preset: ['default', {discardComments: {removeAll: true}}],},canPrint: true
        }),// Extract CSS (extract a CSS file from a JS file) and optimize CSS
      new HtmlWebpackPlugin({
            template: 'template.html',}).//html
Copy the code
{
  collapseWhitespace: true.// Clear HTML whitespace
  keepClosingSlash: true.removeComments: true.removeRedundantAttributes: true.removeScriptTypeAttributes: true.// Remove the default attributes
  removeStyleLinkTypeAttributes: true.useShortDoctype: true
}
Copy the code

8. Webpack resource persistent cache

1. Each static resource file has a unique hash value that stays the same as long as the content remains the same and only changes when the content is modified. ContentHash Takes full advantage of the browser cache and ensures that new HTML and old JS files are not inconsistent

new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css'.// Direct entry to the bundle
            chunkFilename: '[id].[contenthash:8].css'.[id].[contenthash:8].css is extracted as a separate bundle
        }),
   output: {
        path: `${__dirname}/build`.filename: '[name].[hash].bundle.js'.// Direct entry to the bundle
        chunkFilename: '[name].[chunkhash:8].bundle.js'//splitchunks
    },
Copy the code

Focus on the difference between filename and chunkFilename

9. Monitoring and analysis

1. Webpack Chart: visually analyze what each part consists of

2. Source-map-explorer: analyze all js files under Build (open source-map)

3. Speed: speed-measure-webpack-plugin will tell all loaders and plugins the time and call sequence

10.React Loads on demand

Components returned from Suspense are on-demand components used in conjunction with react-Router

function App {
	return <suspense fallback='<div>loading</div>'>
	<xxx>
</suspense>    
}

    
<Route component = {App}></Route>
Copy the code

We don’t need to break it down too much because if we break it down too much we have to send a lot of requests and it affects performance