Webpack is a popular automated build tool and a static module packer, which treats all resources as modules and packs them into static resources according to the relationship between them. All build tools are based on Node.js, like gulp. Related configurations are generally stored in the webpack.config.js file, but some are stored in three files, including general, production environment, development environment configuration, etc.

Webpack running process (source network)

1. Webpack. Config. Js, shell options argument parsing (2) new webpack (options) 3. The run () compiled entry method 4. com from running () 5. Start the make events addEntry () find the js file, 6._addModuleChain() parses the JS entry file to create the module. 7. Loader processing and Acorn processing AST syntax tree 8.seal() each chunk corresponds to an entry file 9.createchunkassets () generates the resource file 10.maintemplate.render () Moduletemplate.render () generates templates. 12.module.source() saves the generated JS in compiler.assets 13.Compiler.emitAssets() outputs the final JS to the path of output through emitAssetsCopy the code

Webpack5 core modules and other modules

(1) entry (2) the output (3) loader (4) the plugins (5) mode and resolve all landowners devServer

The core module

Entry:

Hints Webpack at which file to start packing as the entry point, and analyzes how to build an internal dependency diagram.

Entry has two modes: single entry and multiple entry

(1) entry: ". / SRC/main. Js ", / / single entry mode, write directly path (2) entry: [". / SRC/main. Js ", ". / SRC/index. Js "], / / the entry mode (3) the entry: {/ / the second writing app: ". / SRC/main. Js ", the index: ". / SRC/index. Js "},Copy the code

After executing WebPcak, (1) and (2) are packaged into a chunk. Enter a bundle file. The default name of the chunk file is main.

(3) is in the form of key-value pairs. (3) is more commonly used than (2) and outputs multiple bundles, which is beneficial for code splitting.

A bundle consists of one or more chunks, and a chunk consists of one or more modules

Output:

Hints on where to export webpack-packed resources and how to name them.

Output: {// related configuration, path:./ SRC, // Output directory path (public directory for future output of all resources) filename: {// related configuration, path:./ SRC, // Output directory path (public directory for future output of all resources) filename: "[name].js", // File name plus directory, name represents entry chuank file name publicPath: Public path prefix chunkFilename: non-entry chunk name Library: variable name exposed throughout the library libraryTarget: variable name added to the browser, node. },Copy the code

Mode:

mode:development/production
Copy the code

Development mode: Environments that allow code to be debugable locally will set process.env.node_env = development.

Production mode: An environment in which code can be optimized to run online. process.env.NODE_ENV = production.

loader:

Let Webpack handle non-JS files (Webpack itself only understands JS/JSON, not CSS/IMG).

Use loader must first download before using

Module: {rules: [{test: /\. Vue $/, // re matching file loader: "Vue-loader ", quoting a single loader exclude: does not match any file include: only matches any file oneof: only oneof the following configurations takes effect. Loader configuration}, ]} Common loader csS-loader converts CSS to JS style-loader Inserts style labels into HTML less-loader converts less to JS file-loader Converts other files to JS url-loader Image processing than file one more compressed HTML-loader in HTML transfer imagesCopy the code

Plugins:

Plug-ins can be used to perform a wider range of tasks. Plug-ins range from packaging optimization to compression to redefining variables in the environment.

Plug-ins must be downloaded and referenced before being used.

NPM install html-webpack-plugin --save-dev const HtmlWebpackPlugin = require("html-webpack-plugin"); Plugins: [new HtmlWebpackPlugin({filename: "index.html", template: "index.html", inject: true, favicon: path.resolve(__dirname, "../favicon.ico") }), ]Copy the code

Other modules:

**resolve: ** Resolve module rules

Resolve: {extensions: [", "vue" js ", "json"], / / configuration omit the file path suffix alias: {vue $: "vue/dist/vue. Esm. Js", / / custom path alias "@" : Resolve (" SRC "),}, modules:Copy the code

devServer

Webpakck development server, for development environment only.

devServer: { clientLogLevel: "warning", historyApiFallback: { rewrites: [ { from: /.*/, to: Path. The posix. Join (config. Dev. AssetsPublicPath, "index.html")}}], hot: true, open HMR contentBase: False, / / run the code directory compress: true, open gizp compression host: the host | | config. Dev. Host, domain name server port: The PORT | | config. Dev. The PORT, the PORT open: config. Dev. AutoOpenBrowser, automatically open the browser proxy: config. Dev. ProxyTable, proxy server quiet: True, // The console does not display other information except basic information},Copy the code

Webpack performance optimization

Performance optimization is divided into development environment performance optimization and production environment performance optimization

The development environment

The performance optimization of development environment mainly lies in the optimization of packaging construction speed and optimization of project debugging

Package build speed:

HMR: module update only updates this module, not all files.

Code debugging:

Source-map: build error, error mapping to Source code, easy to find errors, debug friendly.

The production environment

Production environment performance optimization mainly lies in optimizing packaging construction speed and optimizing code performance

Package build speed:

Oneof: js/json allows loader to find only one file instead of each loader looking for execution.

Baber cache: The cache from the first build is used on the second build.

Multi-process packaging: Multiple processes are packaged together, which is faster, but consumes 600ms on their own, only for long builds.

DLL: Specifies that certain content is not packaged.

Code run:

Cache: hash-chunkhash-contenthash to hash the pathname

If you specify a file name, the browser will automatically remember the same file name and cache it. If you change the file name, the browser will update it again.

The server can set the cache time

filename: utils.assetsPath("js/[name].[chunkhash].js")
Copy the code

Automatically removing unnecessary code from your code like console.log and unused imports. Es6 modularity and Mode: Production are enabled.

Lazy loading and preloading

Code splitting + DLL: It is not efficient to divide code into multiple bundles. All the code is placed in the same bundle. It is more efficient to divide code into multiple bundles and call whichever one is used.

There are usually three ways of code segmentation in Webpack: 1. Entry Points: it is the simplest and most direct way to segment code through configuration Entry files. However, this way has certain disadvantages, which may cause repeated packaging of code. 2. Prevent Duplication: Use splitChunksPlugin for common code extraction. Dynamic Imports: Split code with Dynamic code loading, using the import() method. The point where import() is called is taken as the starting point for the split module, meaning that the requested module and all its submodules referenced by it are split into a separate chunk. The import method relies on Promise and needs to be polyfilled if it needs to be used in older browsers.Copy the code