1. User perception optimization

  1. Friendly error

friendly-errors-webpack-plugin

  1. The progress bar

progress-bar-webpack-plugin

  1. A notification is displayed when compilation is complete

webpack-build-notifier

  1. Set window title

set-iterm2-badge

  1. Visually display the WebPack build

webpack-dashboard/plugin

2. Optimization of construction speed

2.1 Narrowing the naming range

Use test, include, and exclude to match the file to which the Loader applies the rule. To minimize file processing by Loader.

  1. throughincludeTo match only which files need to be processed
  2. resolve.modules

Resolve. modules defaults to node_modules, which means to go to the node_modules directory of the current directory to find the desired module. If not, go to the upper directory.. /node_modules, then go to.. /.. /node_modules, and so on.

You can specify an absolute path for storing third-party modules to reduce searches

Resolve: {// Use the absolute path to specify the location of the third party module to reduce the search step // where dirname indicates the current working directory, that is, the project root directory modules: [path.resolve(__dirname,'node_modules')] }Copy the code
  1. resolve.mainFields

Configure the entry file used by the third party module. In order to reduce the search steps, we can set the entry file description field of the fourth party module as little as possible

  1. resolve.alia
  2. resolve.extensions

Some JavaScript runtime environments may have global variables or modules built in, such as jQuery in the script tag:

< script SRC = "path/to/jquery. Js" > < / script >Copy the code

At this point, the global jQuery variable is injected into the web page’s JavaScript runtime environment.

If you want to import and use jQuery from source code that uses modularity, you might need to:

import $ from 'jquery';
$('.my-element');
Copy the code

After the build, we will find that the output Chunk contains the contents of jQuery library, which causes the jQuery library to appear twice, wasting loading traffic. It is better that the Chunk does not contain the contents of jQuery library

Externals can tell us which global variables webpack has configured in the javascript runtime environment without packing them into code.

Module. exports = {externals: {Jquery: 'Jquery'}}Copy the code
  1. module.noParse

Ignore recursive parsing of some files that are not modularized to improve build performance.

  • Increase build speed
  • Tell Webpack to ignore larger libraries directly
  • Omitted libraries cannot have import, require, define import
  1. parser

Because Webpack starts with modular JavaScript files, it has built-in parsing capabilities for modular JavaScript, Support for AMO, CornmonJS SystemJS ES6 Parser attributes allow for more fine-grained configuration of which module syntax is parsed and which is not. The difference with noParse configuration items is that parser is syntactic, whereas noParse only controls which files are not parsed. The parser can be used as follows:

module: {rules: [{test: / \. Js $/, use: ['babel-loader'].parser: {amd)false./ / disable AMDCommonjs:false./ / disable CommonJSThe system:false./ / disable SystemJSHarmony:false.// Disable ES6 import/exportRequireInclude:false./ / disable the require. IncludeRequireEnsure:false./ / disable the require. EnsureRequireContext:false./ / disable the require. The contextBrowserify:false./ / disable browserifyRequireJs:false./ / disable requirejs}}}]Copy the code

2.2 Analyze the execution duration of each Loader and Plugin

speed-measure-webpack-plugin

  1. HappyPack multi-core compilation

Happy Pack (github.com/amireh/happ…) The task is divided into multiple sub-processes for concurrent execution, and the sub-processes send the results to the main process after processing them.

  1. The cache cache – loader

  2. dllplugin

  • Take the basic modules that web pages depend on and package them into separate dynamic link libraries. Multiple modules can be contained in a dynamically linked library.
  • When a module to be imported resides in a dynamic link library, the module cannot be packaged again, but is retrieved from the dynamic link library.
  • All dynamic link libraries that the page depends on need to be loaded.

Access webpack

  • DllPlugin plugin: used to package individual dynamic link library files
  • DllReferencePlugin plugin: Used to introduce the DllPlugin plugin packaged dynamic link library file into the main configuration file.
  1. Use less loader/plugin

  2. source-map

  • In the development environment, cheap-module-eval-source-map
  • Production environment: hidden-source-map
  1. Optimize file listening to ignore files that do not need to be listened on

When listening mode is enabled, by default the configuration Entry file and all Entry recursive dependencies are listened on. Many of these files are in node_modules, because today’s Web projects rely on a large number of third-party modules. So in most cases you can’t edit node_modules files, you can edit your own source files, and a big optimization point is to ignore node_modules files and ignore them.

Related configurations are as follows:

module.export = {
    watchOptions : {
    // files in node_modules that are not listened on
    ignored: /node_modules/,}Copy the code

3. Package output quality

  1. To distinguish the environment

Use the value of the environment variable to determine which branch to execute


if (true) {
    console.log('You are using the online environment');
} else {
    console.log('You are using the development environment');
}
Copy the code

Using Uglifyjs it can be compressed to

console.log('You are using the online environment');
Copy the code

In addition, many packages are optimized for production and development environments

  1. Compression JS
  • UglifyJsPlugin: Compression by encapsulating UglifyJS
  • ParallelUglifyPlugin: Parallel compression for multiple processeswebpack-parallel-uglify-plugin

Compression ES6: uglifyjs webpack — plugin @ beta

uglifyjs-webpack-plugin

  • New version, support ES6 Terser-webpack-plugin
  • Reduce the size of the JS file

Scope promotion (merge scope)

  • Code size reduction
  • Improve execution efficiency
  • Also note the modules configuration of Babel (import only supported)
  1. Babel7 optimized configuration
  • Where needed lead | polyfill (@ Babel/polyfill)
  • Introduction of auxiliary functions on demand
Presets: [['@babel/preset-env', {"useBuiltIns": "usage", // polyfill as needed}],],Copy the code
  • Babel/plugin-transform-Runtime reuses polyfill instead of generating a polyfill every time
  1. Compress CSS

mini-css-extract-plugin optimize-css-assets-webpack-plugin

  1. The CDN to accelerate
module.exports = {
    // omit entry configuration...
    output: {
        // Hash the output JavaScript file name
        filename: '[name][chunkhash:8].js'.path: the path. The resolve (_dirname,'.dist'), specify the URL of the CDN directory where the JavaScript files are storedpublicPath: '//js.cdn.com/id/',}}Copy the code
  1. tree shaking
  • Based on ES6 import export
  • Configure sideEffects in package.json
// Exclude file "sideEffects": ["*.css"]Copy the code
  • Note the impact of the default configuration of Babel
presets: [ [ '@babel/preset-env', { modules: False, // Don't need to convert import to another syntax, because tree-shaking only supports import}], '@babel/preset-react'],Copy the code

The mainFields configuration uses the field as the entry description for the module, we need to use the ES6 version of the third-party package

module.exports = { resolve: MainFields :[' jsNext :main','browser','main']}}Copy the code

The above configuration means that jsNext: main is used as the entry preference. if not, jsNext: main will use browser or main as the entry. While not every third party module in the NPM will provide ES6 modular syntax code, try to optimize the code that is provided.

  1. Extract common code

  2. Split load on demand (asynchronous components, asynchronous routes)

  3. prepack

Preack-webpack-plugin optimizes code execution efficiency (immature, not to be used online)

  1. scope hoisting

Analyze module dependencies and combine possible modules into a function

  1. Persistent cache
  • Each packaged resource file has a unique hash value
  • After the modification, only the hash of affected files changes
  • Take full advantage of the browser cache
  1. Application size monitoring and analysis based on WebPack
  • Stats analysis and visualization
  • Webpack-bundle-analyzer for volume analysis
  • Speed-measure-webpack-plugin Speed analysis