preface

Recently in the study of Webpack, record the basic things learned, as well as the speed and volume of project construction optimization.

Webpack basic configuration

Basic configuration before writing an article, not to write again, do not understand, please refer to the small white webpack.

Modify the code, automatic compilation

  • Webpack — Watch does not refresh the browser, the js package of the development environment is stored on disk.

Package. The json fileWebpack. Dev. Js fileNote: webpack.dev.js // development environment configuration webpack.prod.js // build environment configuration

  • Webpack dev – server – the open will automatically open the browser, need and webpack. HotModuleReplacementPlugin (), code changes, can automatically refresh the browser.

Package. The json fileWebpack. Dev. Js file

Principle of Hot Module Replacement (HMR)

  • Webpack Complier converts code to bundle.js files.
  • Transfer the bound.js file to Bounle Server for Browser Browser access.
  • When the code is updated, the HMR Server passes the code to the HMR Runtime (usually in json form).
  • The HMR Runtime accepts updates to the code and refreshes the browser.

File fingerprint

Package the output filename suffix, usually as version management, without modifying the file, which can be used by the browser cache to accelerate access.

  • Hash: Related to the entire project, the entire project builds a hash that changes whenever the file is modified, usually for images and fonts.
  • Chunkhash: Different entries have different value of chunkhash, which is usually used by JS files.
  • Contenthash: Generates hash values based on file contents, which is usually used by CSS.

Style-loader: inserts CSS into the style tag, into the header, no separate CSS file. MiniCssExtractPlugin(filename:'[name][conetnthash:8].css’).loader pulls CSS out of a separate file and links it to the header. webpack.prod.js

Code compression

  • The uglifyjs-webpack-plugin plugin is used by default and packaged in ES6.
  • HTML, using the html-webpack-plugin (one HTML template corresponds to one html-webpack-plugin)
  • CSS, using the optimize- CSS – Assets -webpack-plugin, with CSSNano

Css3: Automatically add browser prefix (AotuperFixer)

Px in CSS on mobile is converted to REM

  • Rem: relative unit, (font size relative to the root HTML element)
  • Px: absolute unit
  • Px2rem: Change px to REM

  • Lib-flexible: dynamically computes the font size of the root element

Import import ‘lib-flexible’ in import file

Multi-page application (Entry + HTML-webpack-Plugin)

Set entry dynamically, htML-plugin-webpack, use glob library, glob.sync() to get the directory information of the regular match synchronously.

Source map locates the source code

It is enabled in the development environment and disabled in the production environment. webpack.prod.js

Optimize the command line log display at build time

Stats in webpack: Use friendly-errors-webpack-plugin to set stats to ‘error-only’

Webpack advanced usage

Extract common resources

  • The react, react-dom and other common libraries are imported into bounld.js using the html-webpack-externals-plugin via CDN
new HtmlWebpackExternalsPlugin({
 externals: [
    {
      module: 'react',
      entry: 'https://unpkg.com/react@17/umd/react.production.min.js',
      global: 'react',
    },
  ],
}) 
Copy the code
  • The splitchunk attribute of WebPack4 is used to separate common scripts. Splitchunk can also extract functions encapsulated by itself that are used in common use. However, multiple functions need to be packaged into the library and used at the same time.
optimization:{ splitChunk:{ minSize:0, CacheGroups: {vendor: {/ node_modules/extraction test of public resources: / / \ \ / node_modules / \ \ / (react | react - dom) \ \ / /, name: 'vendor', Chunks :'all'}, Commons :{// extract node_modules and self-written notification functions. Chunks:' all', name:' Commons ', minChunks:'2'}}}}Copy the code

Tree shaking

Only ES6 syntax is supported. Production for Webpack4 is turned on by default. Reason: Analyze code statically instead of analyzing what is not used while it is running, comment out useless code in the Tree shaking phase, and remove useless code in the code compression phase.

Using the features of ES6 module:

  • Import can only appear at the top level of a module
  • The module name of import must be a string constant (cannot be changed after import)
  • Import binding is immutable (cannot be dynamically imported)

Note: Dynamic require imports cannot be implemented in code

DCE(dead code elimination)

  • Code unreachable
  • Code execution results are not used
  • The code only affects dead variables (write, not read)

The Scope Hositing (/ ˈ h ɔ ɪ st ɪ ŋ /)

Production for Webpack4 is turned on by default and must use ES6 syntax without CJS support.

What problems will occur if the Scope collieries are not opened:

  • A large amount of closure function code can lead to larger code after a build
  • The functions created while running the code have more scope and more memory overhead

Principle of scope collieries:

Put all module code in a function scope in reference order, and rename some variables appropriately to place variable name conflicts.

Comparison: After the code is processed by Scope Hositing, the function declaration code and memory overhead are reduced.

Note: if the module is used only once, it will be directly inlined in the function scope. If it is used more than once, a new function scope will be created.

The code segment

It is not efficient to pack all the code into a single file, especially if some of the code is used in special situations. Webpack can break the packaged code into chunks and load the code while it is running.

Webpack packages the component library

A simple component library rollup is more suitable

Release NPM package

  • You need to package the compressed and uncompressed versions
  • Need to support AMD/CJS/ESM module import, set output library to ‘umD’.

Webpack. Config. Js configuration

NPM release steps

  • npm login/ / login
  • npm publish/ / release package
  • npm version path// Fix bugs and patch
  • npm version minjor// Create a feature and update it with a small version number
  • npm version major// Upgrade a large version

Semantic Versioning format specification

  • Major version number: as a change to an incompatible API
  • Version number: as a backward compatible functionality addition
  • Revision number: fixed as a problem with backward compatibility

Prior version number

  • Alpha: is the internal beta version, generally not released to the outside, there will be a lot of bugs, generally only for testing.
  • Beta: Also known as the beta release, this phase of the release is improved over the alpha release, eliminating serious bugs, but still has defects, this release will always add new features, after the alpha release.
  • Rc: a platform release candidate with no new features, focusing on troubleshooting.

Webpack build speed

Speep-measure -webpack-plugin Speed analysis function: You can view the execution time of each loader and plug-in and the total packaging time.

Project speed increase

1. Use older versions of WebPack and Node

2. Multi-process multi-instance construction

Thread-loader (recommended for WebPack4). Each time webpack parses a module, thread-loader assigns it and its dependencies to worker threads.3. Compress multi-process instances

Terser-webpack-plugin Sets the paralled parameter4. Subcontracting: precompile resource modules

Use dllPlugin, dllReferencePlugin, and script to introduce packaged DLL files. Create the webpack.dll.js fileIn package.json fileperformnpm run dll, the public package files are generated.

In webpack. Dev. Js, webpack. Prod. Js configuration can (when hit multiple files, each file you need to add a plug-in, in this paper, we only pack to a file)

5. Leverage caching to improve secondary builds

  • Babel – Laoader enables caching
  • Terser-webpack-plugin enables caching
  • Use the hard – source – webpack – the plugin

6. Reduce file search scope resolve. Modules, resve. MainFields, resolve. Extensions, resolve. Alias configuration.

Webpack builds volumes

Webpack-bundle-analyzer analyzes the size of the third party dependencies, and the size of our own component code

Project volume optimization

1. Image compression

Use the image – webpack – loader

2. Delete unnecessary CSS

  • PurifyCSS: Walk through the code, identify the CSS used, use purgecss-webpack-plugin (CSS cannot be used)
  • Uncss: HTML is loaded using jsDOM, styles are parsed using postCSS, and document.querySelect is used to identify selectors that do not exist in HTML files.

3. Extract common resource modules

See webPack speed up subcontracting: Precompiled resource modules

conclusion

Practice and optimization of Webpack, sort out knowledge points, and continue to add in later study.