Packing Volume Optimization webpack

webpack packaged volume is smaller, the website for application deployment, the better the performance, load faster.

1. Analysis of packed files

1. Generate statistics files

First you need to generate file statistics by webpack command. Add a command script in package.json

  "scripts": {
    "stats": "webpack --config webpack.prod.js --profile --json > stats.json", 
     //...
  }

The above command will generate a file package statistics stats.json in the root directory.

2. visual analysis

Visual analysis using a plug-in plug-ins: webpack-bundle-analyzer

npm install --save-dev webpack-bundle-analyzer

Use plug-in configuration information;

the require BundleAnalyzerPlugin = const ( 'the bundle-WebPACK-Analyzer' ) .BundleAnalyzerPlugin; 

module.export = {
    // ... 
  plugins: [
     new new BundleAnalyzerPlugin ({ 
      analyzerMode: 'Disabled',   // Close http server presents the information default start 
      generateStatsFile: to true   // package files when generating stats.json; 
  }) 
}

Configuration seen from the above information, the use of the plug, do not need to manually generate stats.json file, the first step may be omitted.

Then, manually start the script http analyzer

// analysis using the command should be after the packaging commands. Because its role is to analyze files packed 
 "scripts" : {
     "Build": "WebPACK --config webpack.prod.js" ,
     "Analyzer": "WebPACK-bundle-Analyzer ./dist/stats.json - 8081 Port " 
  }

3. Optimization Tips

The resulting stats.json file into the site https://webpack.jakoblind.no/optimize/ .

It will give a bulky package of optimization measures.

The plug-in based webpack-optimize-helper plugin.

2. pulled out and compress css

1. pulled css

Use mini-css-extract-plugin pulled css

npm install --save-dev mini-css-extract-plugin

The use of plug-in plugins configuration file

= module.exports { 
  plugins: [ 
    new new MiniCssExtractPlugin ({ 
      filename: 'css / [name] [contenthash:.. 8] .css'   // be unified into css css file folder 
    }) 
  ]   
}

2. Compression css

Use optimize-css-assets-webpack-plugin css file compression

npm install -D optimize-css-assets-webpack-plugin

Using this plug-in optimization in

module.exports = {
    optimization: {
        minimize: true,
        minimizer: [
            new OptimizeCssAssetsWebpackPlugin()
        ]
    }    

3. Remove unused css

In large projects, there is often a lot of style content, do not use in your code, but will be packaged, these styles should be removed when packaging needs.

Use purgecss-webpack-plugin css remove unused styles.

npm i purgecss-webpack-plugin -D

Configuring the plug-in pluigns

the require glob = const ( 'glob'); // find the file based on the path 
module.exports = { 
  plugins: [ new new PurgecssWebpackPlugin ({ // Paths requirement is absolute paths: glob.sync ( `$ {path.join (__ dirname, 'the src / ** / *') `}, {nodir: to true }) })
]

3. runtime code with the multiplexed conversion when babal

@babel/plugin-transform-runtime

✅ the introduction of the plug-in can only be .babelrc file, not in the options babel-loader in, otherwise an error.

4. Use CDN

1. The use of third-party libraries CDN

    new HtmlWebpackExternalsPlugin({
      externals: [
        {
          module: 'lodash',
          global: '_',
          entry: 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js'
        }
      ]
    })

To avoid the user manual and then introduced into the module, add

  externals: {
    lodash: '_'
  },

2. The project generated static file server can be deployed CDN

CDN server needs to be configured for the domain name publicPath

// Output, module-> MiniCssWebpackLoader.loader, and the like can be deployed Image publicPath 
publicPath: 'http://lyralee.com'

5. webpack.IgnorePlugin

Ignore unwanted third-party library folder.

new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)

Above ignores the moment the library Language Pack

6. Image compression image-webpack-loader

      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 2 * 1024,
              outputPath: 'images',
              name: '[name].[contenthash:8].[ext]'
            }
          },
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true,
                quality: 65
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: false
              },
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4
              },
              gifsicle: {
                interlaced: false
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75
              }
            }
          }
        ]
      }

7. Use of alternative babel-polyfill

If the project is allowed to use external links, you can use

<script src="https://polyfill.io/v3/polyfill.min.js/"></script>

It returns the contents required in accordance with the type of browser

 8. TreeShaking

1. Principle:

1) using the static structure es6 module, module commands dependent on import / export, code analysis, the useless / never access codes.

1 ) to write their own code to prohibit the esModule into babel The require 
rules: [ 
      { 
        the Test: /\.jsx?$/ , 
        use: { 
          Loader: 'babel-Loader' , 
          Options: { 
            // set {moduels: false } is retained import / export ES6 the 
            Presets: [[ '@ Babel / PRESET-the env', {modules: to false } ], '@ Babel / PRESET-REACT' ], 
            plugins: [ 
              [ '@ Babel / plugin-proposal- Decorators', {Legacy: to true }], 
              [ '@ Babel / plugin-class-Properties-Proposal', {Loose: to true }]  
            ]
          }, 
        }, 
        The exclude: / the node_modules / 
      } 
    ] 
2) For third-party libraries, use packages es module, such as: lodash- es (there is a problem, not the first) 
Import {} from the Join ' lodash-es '

2) removing redundant code analyzed by terser-webpack-plugin

// ⚠️ Just write the optimization property (even empty), even in production, it will not start the Terser plug; if it is complete configuration, but the mode = development, the property does not function 
optimization: { 
    Minimizer: [ 
      new new TerserWebpackPlugin ({ 
        Parallel: to true , 
        Cache: to true 
      }) 
    ], 
     ... 
  },

2. Considerations

1. To make the TreeShaking work, you must use the syntax ES6 Import / Export 
2. reduce sideEffects (side effects) code written in 
third-party libraries 3. introduced the need to introduce their version of ES

3. Special circumstances

When a plurality of inlet file exists, as long as there is one inlet using a certain method, it will not be lost TreeShaking

9. Code division

1. file code division inlet

entry: {
    index: './src/index.js',
    vendors: ['lodash']
}

2. Dynamic introduced import implemented lazy loading

When the trigger code used import () introduced into the dynamic file, initiates the request, and returns a webpackJsonp method,

The method implemented in the code loaded on demand.

Further, React16.6.0 introduced React.lazy () is implemented in the code module based on the segmentation and lazy loading method.

3. Use splitChunks plug

splitChunks: { 
      cacheGroups: { 
        vendors: { 
          of chunks are: 'Initial', // there aysnc / all mode 
          name: 'vendors', // override the default name generated 
          Test: / the node_modules / , 
          priority: -10, // priority level 
          the minSize: 1024 * 100   // generates a separate file minimum volume 
        }, 
        Commons: { 
          of chunks are: 'Initial' , 
          name: 'Commons' , 
          : priority -10 , 
          minChunks: 2, // minimum number of referenced modules
          minSize: 50*1024
        }
      }
    }

Guess you like

Origin www.cnblogs.com/lyraLee/p/12031076.html