preface

As a front-end programmer, it is unavoidable to deal with a variety of frameworks in daily development, and the use of the framework needs to use scaffolding, such as the use of VUE CLI. If we need to enhance functions on the basis of existing scaffolding in the development process, we will definitely need to use the knowledge of WebPack, because almost popular frameworks such as Vue and React scaffolding are built based on WebPack.

So learning webpack knowledge is not unimportant.

This article will take you through building a usable Webpack from scratch, helping you comb through the basics of WebPack and how to optimize your project with it.

Basic concept of Webpack

1.1 What is Webpack?

Simply put, WebPack is a front-end resource builder, a static Module bundler. In webpack’s view, all the front-end resource files (JS /json/ CSS /img/less/…) Will be treated as modules. It will carry out static analysis according to module dependencies and generate corresponding static resources (bundles).

1.2 What are bundle, Module, and chunk in Webpack?

Summary: Module, chunk, and bundle are the same logical code with three names in different transformation scenarios:

We write modules directly, webpack processes chunks, and finally generate bundles that the browser can run directly.

In order to avoid this article is too long, here is only the conclusion, related to the process you can go to see this article:

What are bundle, module, and chunk in Webpack

1.3 What are Loader and Plugin in Webpack?

Loader: Enables Webpack to handle non-JS files, such as style files, image files (Webpack only understands JS)

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

  • Difference between loader and plugin :(plugin must be introduced first to use)

    Loader: 1. Download 2. Use (Configure loader)

    In the early days of the New Year, plugins were found to have become more popular

Core concept of Webpack

2.1 entry

Entry: Indicates which file webPack starts packing as the Entry point, analyzing and building internal dependency diagrams.

Three forms:

  1. String –> ‘./ SRC /index.js’, single entry packed to form a chunk. Output a bundle file. The default name of chunk is main
  2. Array –> [‘./ SRC /index.js’, ‘./ SRC /add.js’]. (Usually only used in HMR to enable HTML hot updates)
  3. Object: Multiple entries Several entries form several chunks and output several bundle files. In this case, the name of chunk is the key value

–> Special usage:

Entry: {// Only one chunk is generated and only one bundle is exported. Index: ['./ SRC /index.js', './ SRC /count.js'], // form a chunk and output a bundle file. add: './src/add.js' }Copy the code

2.2 the output

Output: Indicates where the Output of resource bundles packaged by Webpack goes and how to name them.

Output: {// filename (specify name + directory) filename: 'js/[name].js', // output file directory (public directory for future output of all resources) path: Resolve (__dirname, 'build'), // all resources introduce publicPath prefix --> 'imgs/a.jpg' --> '/imgs/a.jpg' publicPath: '/', chunkFilename: 'js/[name]_chunk.js', // Specify the name of the non-entry chunk library: '[name]', // The variable name exposed after packaging the entire library libraryTarget: Browser: window // libraryTarget: 'global' // node: global // libraryTarget: 'commonjs' // conmmonjs module exports},Copy the code

2.3 the module

Use use: ['style-loader', 'css-loader']}, {test: ['style-loader', 'css-loader']} /\.js$/, // exclude: /node_modules, // include: resolve(__dirname, 'SRC '), enforce: 'pre', // precedence // Enforce: 'post', // postpone execution // single loader use loader: 'eslint-loader', options: {} // Specify configuration options}, {// Only one oneOf: []}]},Copy the code

2.4 resolve

Resolve: {// Configure the resolve module path alias: Advantage: abbreviate the path when the directory level is complex; Alias: {$CSS: resolve(__dirname, 'SRC/CSS ')} ['. Js', 'json', 'JSX', 'CSS'], / / tell webpack parsing module should go to which modules directory: [resolve(__dirname, '../../node_modules'), 'node_modules'] }Copy the code

2.5 dev server

DevServer: {// Run code directory contentBase: Resolve (__dirname, 'build'), // Monitor all files in contentBase, reload watchContentBase: true, watchOptions: Ignored: /node_modules/}, // Start gzip compress: true, // Port: 5000, // host: 'localhost', // automatically open browser open: true, // enable HMR function hot: true, // Do not display startup server log information clientLogLevel: 'none', / / in addition to some basic information, other content don't display the -quiet: true, / / if make a mistake, not full screen tip overlay: false, / / server agent, - > solve the problem of development environment cross-domain proxy: // Once devServer(5000) receives a request for/API/XXX, it forwards the request to another server 3000 '/ API ': {target: 'http://localhost:3000', // request pathRewrite: / API/XXX --> / XXX (remove/API) pathRewrite: {'^/ API ': '}}}} 'Copy the code

2.6 optimization

Optimization: {splitChunks: {chunks: 'all', /* This is the default configuration of splitChunks. MaxSize: 0, minChunks: 1 without limitation, // Chunks to be extracted can be referenced at least once. MaxAsyncRequests: MaxInitialRequests: 3, // maxInitialRequests: 3, // automaticNameDelimiter: '~', // CacheGroups: {// Groups dividing chunks, vendors: {// files in node_modules are packed into vendors group chunks, --> vendors~xxx.js // Satisfy the common rules above, exceed 30KB in size, and be referenced at least once by test: /[\\/]node_modules[\\/]/, // Priority: -10}, default: { -20, // If the current module to be packaged is the same as the previously extracted module, it will be reused instead of reuseExistingChunk: RuntimeChunk: {name:}}} */}, // Package the hash value of the index. entrypoint => `runtime-${entrypoint.name}` }, minimizer: [// configure the production environment compression scheme: js/ CSS new TerserWebpackPlugin({// enable cache: true, // enable multi-process packaging parallel: True, // enable sourceMap(otherwise compressed) sourceMap: true})]}Copy the code

2.7 mode

Mode: Instructs Webpack to use the configuration of the corresponding Mode.

options describe The characteristics of
development The value of process.env.node_env in DefinePlugin is set to development. Enable NamedChunksPlugin and NamedModulesPlugin. An environment in which code debugging can run locally
production The value of process.env.node_env in DefinePlugin is set to production. Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and TerserPlugin. An environment that optimizes code to run online

Note: there is no need to memorize all of the above configuration, but refer to this article or the official website when you use it. Learning webpack in this way will get twice the result with half the effort.

3. Basic use of Webpack

With the basic concepts out of the way, let’s give WebPack a try.

3.1 Initial Configuration

  1. Initialize package.json: NPM init
  2. Download and install WebPack: (WebPack 4 or later requires webpack -CLI installed globally or locally.) Global installation: CNPM I webpack webpack-cli -g Local installation: CNPM I webpack webpack-cli -d

Note: Here are two suggestions for you.

  • Try to use a local installation to make it easier to use different versions of WebPack for different projects
  • Try to install the dependency of the lower version, such as webpack 4 version and Webpack CLI 3 version I use here, and other versions such as less and less-loader should also try not to use the latest version, because as some novices, our starting point is to learn, so the primary purpose is to make the project run as much as possible.

Create a new folder SRC, then create a new file main.js, write a little code to test console.log(‘ hey hey ‘)

Configure the package.json command

perform

npm run build
Copy the code

If you generate a dist folder with main.js inside it, you have successfully packaged it

This is the most basic use of WebPack, but it’s still a bit far from official use.

Let’s go through the basic configuration of the development environment.

4. Basic configuration of Webpack development environment

Webpack.config.js is the webpack configuration file.

What it does: Tells webpack what to do (when you run webpack, it loads the configuration inside)

All build tools run on the NodeJS platform, and commonJS is the default for modularity.

The development environment is configured primarily to enable code to run. The following aspects are mainly considered:

  • Packaging HTML resources
  • Package style resources
  • Package image resources
  • Package other resources
  • devServer

Create a new webpack.config.js file in SRC

// webpack.config.js const path = require('path'); Module. exports = {mode:'development', // Development mode entry: path.resolve(__dirname,'.. / SRC /js/index.js'), // import file output: {filename: 'js/build.js', // package filename path: Path.resolve (__dirname,'build') // Packaged directory},}Copy the code

Change our packaging command

NPM run build generates the following directory where main.js in the dist folder is the file we need to actually run in the browser

4.1 Packaging HTML resources

Webpack does not recognize HTML files, so we need to install a plug-in called html-webpack-plugin

npm i html-webpack-plugin -D
Copy the code

The HTML-webpack-plugin does two things for us

  • By default, an empty HTML file is created and a template, if any, is copied
  • Automatically import all resources (JS/CSS) that are packaged for output

We can create index. HTML in

The configuration files are as follows

// webpack.config.js const path = require('path'); Const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = {mode:'development', // development mode entry: path.resolve(__dirname,'.. / SRC /js/index.js'), // import file output: {filename: 'js/build.js', // package filename path: Path.resolve (__dirname,'build') // packaged directory}, plugins:[ new HtmlWebpackPlugin({ template:path.resolve(__dirname,'./src/index.html') }) ] }Copy the code

4.2 Package style resources

Webpack cannot recognize CSS files, so we need to install two Loaders, style-Laoder and CSS-Loader

npm i -D style-loader css-loader
Copy the code

If we use less to build the style, we need to install two more

npm i -D less less-loader
Copy the code

Loaders are executed from right to left and from bottom to top (csS-loader is executed first)

Style-loader: creates a style tag, inserts the js style resource, and adds it to the head to take effect

Css-loader: Loads a CSS file as a CommonJS module into js, which contains style strings

Less-loader: To compile less files into CSS files, you need to download less-loader and less

The configuration file is as follows

// webpack.config.js module.exports = { // ... Omit the other configuration module: {rules: [{$/ test: / \. CSS, use: [' style - loader ', 'CSS - loader'] / / analytical principles from right to left}, {test: / \. Less $/, Use :['style-loader','css-loader','less-loader'] // Right-to-left parsing principle}]}}Copy the code

4.3 Package image resources

Webpack cannot recognize image files, so we need to install two URl-loaders, file-loaders

File-loader parses the file import/require () into a URL and emits the file to the output directory.

Url-loader recognizes the size of the image and converts it to Base64 to reduce the size of the code. If the image exceeds the specified size, file-loader is used again.

// webpack.config.js module.exports = { // ... Omit the other configuration module: {rules: [{test: / \ | PNG (jpe? G | GIF) $/ I / / picture file use: [{loader: 'url - loader, the options: {limit: 10240, fallback: { loader: 'file-loader', options: { name: 'img/[name].[hash:8].[ext]' } } } } ] } ] } }Copy the code

4.4 Package other resources

File-loader can package other resources such as fonts, videos, and audio in addition to images.

{/ / | | js | CSS rule out HTML less | JPG | PNG | GIF file exclude: / \. | | js | (HTML CSS less | JPG | PNG | GIF) /, / / file - loader: handle other file loader: 'file-loader', options: { name: '[hash:10].[ext]', outputPath: 'media', },Copy the code

devServer

In addition to the above resource packaging, we also need to use the development server devServer for ease of development.

npm i webpack-dev-server -D
Copy the code

DevServer: for automation, you don’t have to re-enter Webpack every time you change it (auto-compile, auto-open browser, auto-refresh browser)

Features: Packages are only compiled in memory, with no output (you will not see the package outside as before, but in memory, it will be automatically deleted when closed)

Start devServer with NPX webpack-dev-server

Here is a simple development environment webpack.confg.js configuration file

Const {resolve} = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') // Exports = {// webpack configuration entry: './ SRC /js/index.js', // 'js/build.js', // __dirname is the nodejs variable and represents the absolute path of the current file directory: // resolve(__dirname, 'build'), // all resources will be output to this folder}, // loader configuration module: {rules: [// detailed loader configuration // Different files must be configured for different loader processing {// which files match test: /\.less$/, // which loader is used for processing use: [// use array loader execution sequence: right to left, bottom to top (csS-loader first) // style-loader: Create style tag, insert js style resource, add to head 'style-loader', // css-loader: // less-loader: // class-loader: // class-loader: // class-loader Less 'less-loader'],}, {test: /\. CSS $/, use: ['style-loader', 'css-loader'],}, {// url-loader: / \. (JPG | PNG | GIF) $/, / / need to download url - loader file - loader loader: 'url - loader, the options: {// Images smaller than 8KB will be base64 processing, advantages: reduce the number of requests (reduce server stress), disadvantages: // Base64 decoding in the client will reduce the server pressure, if the image is too large and base64 encoding will cause CPU call rate increase, webpage load time change card limit: 8 * 1024, // Rename the image, [hash:10] : take the first 10 bits of the hash of the image, [ext] : take the original extension name of the file: '[hash:10].[ext]', // Problem: Url-loader uses es6 Module by default, htMl-loader uses conmonjs. Disable URL-loader es6 modularity and use CommonJS to resolve esModule: false, outputPath: 'imgs',},}, {test: /\.html$/, // handle the img image of the HTML file (responsible for importing img, which can be processed by urL-loader). 'HTML - loader,}, / / packaging other resources (in addition to the HTML/js/CSS outside resources) {/ / | | js | CSS rule out HTML less | JPG | PNG | GIF file exclude: / \. | | js | (HTML CSS less | JPG | PNG | GIF) /, / / file - loader: handle other file loader: 'file - loader' options: {name: '[10] hash: [ext]', outputPath: 'media',}},],}, / / the plugin to configure plugins: [/ / HTML - webpack - the plugin: HtmlWebpackPlugin({// copy this./ SRC /index.html file); // Add a template new HtmlWebpackPlugin({// copy this./ SRC /index.html file, Template: './ SRC /index.html',}),], // mode: 'Development ', // development mode // devServer: used for automation, no need to re-enter webpack after each change (automatically compile, automatically open browser, automatically refresh browser) // Features: NPX webpack-dev-server devServer: NPX webpack-dev-server: NPX webpack-dev-server: {// project build path contentBase: resolve(__dirname, 'build'), // gzip compress: true, // port: 3000, // automatically open browser: true, }, }Copy the code

Most of these configurations are explained in comments.

  • NPX webpack-dev-server will only compile the package in memory, with no output

Basic configuration of Webpack production environment

The configuration of the production environment needs to consider the following aspects:

  • Extract CSS into a separate file
  • CSS Compatibility
  • Compress CSS
  • Js syntax check
  • Js Compatibility processing
  • Js compressed
  • HTML compression

5.1 Extract CSS into a separate file

npm i -D mini-css-extract-plugin
Copy the code

The configuration file is as follows

Before WebPack 4.0, we used the extract-text-webpack-plugin to extract CSS styles from JS files into separate CSS files. After WebPackage 4.0, it is recommended to use the mini-CSs-extract-plugin to package CSS files

const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { //... Module: {rules: [{test: /\. Less $/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'less-loader' ], } ] }, plugins: [ new MiniCssExtractPlugin({ filename: "css/built.css", }) ] }Copy the code

5.2 CSS Compatibility

Postcss-loader: CSS Compatibility: postCSS –> Required installation: postCSs-loader postCSs-preset -env

Postcss needs to load the specified CSS compatibility styles through the configuration in package.json in Browserslist

Define browserslist in package.json:

"Browserslist ": {// development environment --> Set the node environment variable: process.env.node_env = development" development": "Last 1 Chrome version", "last 1 Firefox version"," Last 1 Safari version"], // Production environment. Default is production environment "production": [// need to meet most browsers compatible ">0.2%", "not dead", "not op_mini all"]},Copy the code

The configuration file is as follows

const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { //... Omit the other configuration module: {rules: [{test: / \. Less $/, use: [MiniCssExtractPlugin loader, 'CSS - loader, {loader: 'postcss-loader', options: {ident: 'postcss', // () = > [/ / postcss plugins require (' postcss - preset - env) ()],}, 'less - loader'],}}], plugins: [ new MiniCssExtractPlugin({ filename: "css/built.css", }) ] }Copy the code

5.3 Compress CSS

npm i OptimiziCssAssetsWebpackPlugin -D
Copy the code

The configuration file is as follows

Const OptimiziCssAssetsWebpackPlugin = the require (' optimizi - CSS - assets - webpack - plugin ') / / new omit configuration OptimiziCssAssetsWebpackPlugin ()Copy the code

5.4 Js syntax check

If a file is to be processed by multiple Loaders, you must specify the order in which loader executes esLint and then Babel (use Enforce).

Eslint-loader eslint Eslint-config-airbnb-base eslint-plugin-import is required to set the check rule: Set in eslintConfig in package.json

"EslintConfig ": {"extends": "airbnb-base", // Extends airbnb style specification "env": {"browser": true}}Copy the code

The configuration file is as follows

module.exports = { //... {rules: [test: /\.js$/, exclude: /node_modules/, // ignore node_modules enforce: 'pre', // take precedence over loader: 'eslint-loader', options: {// automatic fix: true,},},]},Copy the code

5.5 Js Compatibility processing

Js compatibility processing: need to download babel-loader@babel /core

  1. Basic JS compatibility handling –> @babel/preset-env problem: Only basic syntax can be converted, such as promise advanced syntax cannot be converted
  2. All js compatibility handling –> @babel/polyfill problem: just solve part of the compatibility problem, but to introduce all the compatibility code, too large
  3. If you need to do compatibility, do it: load on demand –> core-js
module.exports = { //... Rules: [{// Exclude: /node_modules/, loader: 'babel-loader', options: Presets: ['@babel/preset-env', // Presets: ['@babel/preset-env', // Presets: ['@babel/preset-env', // Presets: {useBuiltIns: 'usage', // Corejs: {version: 3}, // specify targets: {// Specify which browser version is compatible with Chrome: '60', Firefox: '50', IE: '9', Safari: '10', edge: '17'},},],},},]},Copy the code

5.6 Js compressed

Automatic js compression in production environment

mode: 'production'
Copy the code

5.7 HTML compression

New HtmlWebpackPlugin({template: './ SRC /index.html', // compress HTML code minify: {// collapseWhitespace: True, // removeComments removeComments: true,},}),Copy the code

Vi.Webpack performance optimization

6.1 Optimize packaging construction speed

6.1.1 oneOf

OneOf: no backward matching is performed on the loader to optimize the packaging and construction speed of the production environment

Module: {rules: [{// js syntax check test: /\.js$/, exclude: /node_modules/, // Enforce: 'pre', loader: 'eslint-loader', options: { fix: True}}, {// oneOf optimise the speed of packaging build in production environment // only oneOf the following loader will match (after matching) // note: OneOf: [{test: /\. CSS $/, use: [...commonCssLoader]}, {test: [...commonCssLoader] /\. Less $/, use: [...commonCssLoader, 'less-loader']}, {// js compatibility test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', corejs: {version: 3}, targets: { chrome: '60', firefox: '50' } } ] ] } }, { test: /\.(jpg|png|gif)/, loader: 'url-loader', options: { limit: 8 * 1024, name: '[hash:10].[ext]', outputPath: 'imgs', esModule: false } }, { test: /\.html$/, loader: 'html-loader' }, { exclude: /\.(js|css|less|html|jpg|png|gif)/, loader: 'file-loader', options: { outputPath: 'media' } } ] } ] },Copy the code

6.1.2 Babel cache

Babel cache: Similar to HMR, caching Babel processed resources (updating where JS changes, and other JS using previously cached resources) to make the second package build faster

Code:

{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', corejs: { version: 3 }, targets: { chrome: '60', firefox: '50'}}]], // enable Babel cache // a second build will read the previous cache cacheDirectory: true}},Copy the code

File resource cache

If the file name remains the same, the request will not be rerequested, but the previously cached resource will be used again

1. Hash: mainly used in the development environment, in the process of build, when you have a project file found to change, modify the hash value of the entire project will do (the hash value of the whole project is the same), like this, every time update, will not let the browser cache file, to ensure the file update rate, improve the development efficiency.

Problem: Repackaging changes the HSAH value of all files, invalidating all caches. (Only one file may have been changed)

2. Chunkhash: Indicates the hash value generated by chunk. The hash values from the same chunk are the same

Problem: JS and CSS come from the same chunk and have the same hash value (csS-loader will load CSS files into JS, so they belong to the same chunk)

3. Contenthash: Generates hash values based on file contents. Different files must have different hash values (the hash in the file name changes only when the file content changes)

If the content of the CSS file is changed, the hash value of the packaged CSS file name will change, while the HASH value of the JS file will not change, so the CSS and JS cache will decide separately whether to request the resource again -> let the code live and the cache will be more useful

6.1.3 Multi-process Packaging

Multi-process packaging: If a task takes a long time, it will lag. Multiple processes can do multiple things at the same time, which is more efficient.

The advantage is increased packaging speed, the disadvantage is that each process starts and communicates overhead (babel-loader takes the most time, so it is optimized with thread-loader)

{ test: /\.js$/, exclude: /node_modules/, use: [/* Babel-loader] [/* Babel-loader] [/* Babel-loader] [/* Babel-loader] [/* Babel-loader] */ {loader: 'thread-loader', options: {workers: 2 // process 2}}, {loader: 'babel-loader', options: {presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', corejs: { version: 3 }, targets: { chrome: '60', firefox: '50'}}]], // enable Babel cache // on the second build, the previous cache is read cacheDirectory: true}}]},Copy the code

6.1.5 externals

Externals: enables some libraries to be imported through the CDN without being packaged

Webpack.config.js:

Externals: {// reject library name -- NPM package name jQuery: 'jQuery'}Copy the code

Need to be introduced in index.html via CDN:

< script SRC = "https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js" > < / script >Copy the code

6.1.6 DLL

DLL: Let some libraries be packaged separately and imported directly into the build. You can split node_modules in code split and then use DLL for finer segmentation to optimize the performance of code operation.

Webpack.dll. Js configuration :(pack jquery separately)

/* node_modules libraries are bundled together, but many libraries are too large to package the output JS files. When running webpack, the default is to look for the webpack.config.js configuration file required: / const {resolve} = require('path'); / / resolve = require('path'); const webpack = require('webpack'); Module.exports = {entry: {// / ['jquery'] --> jquery, jquery: ['jquery']}, output: {// filename: '[name].js', // name is jquery path: resolve(__dirname, 'DLL '), '[name]_[hash]', // What is the name of the content exposed in the packaged library}, plugins: [// Package to generate a manifest.json --> Provide jquery mapping (tell Webpack: jquery does not need to pack and expose the name of the content) new webpack.dllPlugin ({name: '[name]_[hash]', // Map library exposed content name path: resolve(__dirname, 'DLL /manifest.json') // output file path})], mode: 'production'};Copy the code

Webpack.config. js configuration :(tell webpack that jquery is no longer needed and export the previously packed jquery to the build directory along with other packed resources)

Const webpack = require('webpack'); const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin'); // Plugins: [new HtmlWebpackPlugin({template: ' '. / SRC/index. HTML}), / / tell webpack which libraries don't participate in the packaging, use at the same time also have to change the name of the new webpack. DllReferencePlugin ({manifest: Resolve (__dirname, 'DLL /manifest.json')}), And in HTML automatically is introduced into the resources of new AddAssetHtmlWebpackPlugin ({filepath: resolve (__dirname, 'the DLL/jquery. Js)})],Copy the code

6.2 Optimize the performance of code operation

6.2.1 Tree shaking

Tree shaking: Remove useless code

Prerequisites: 1. Must use ES6 modularization 2. Enable production environment (this will automatically remove useless code)

Effect: Reduces code size

Configure in package.json:

“SideEffects “: false means all code has no sideEffects.

This can cause problems: CSS / @babel/polyfill files can be dried out (side effect)

So you can configure “sideEffects”: [“*.css”, “*.less”] not shaking CSS /less files tree

6.2.2 Code split

Code segmentation. Breaking a large bundle.js file that packages output into smaller files allows multiple files to be loaded in parallel, faster than loading a single file.

1. Multi-entry split

Bundle index: './ SRC /js/index.js', test: './ SRC /js/test.js'}, output: {// [name] : select filename: 'js/[name].[contenthash:10].js', path: resolve(__dirname, 'build')}Copy the code

2. Optimization:

optimization: {
    splitChunks: {
      chunks: 'all'
    }
  },
Copy the code
  • Package the code in node_modules separately (over 30KB)
  • Automatic analysis of multi-entry chunks, whether there are public files. If there is, it will be packaged as a separate chunk(for example, if jquery is introduced in both modules, it will be packaged as a separate file) (size over 30KB)

3. Dynamic import syntax:

/* Dynamic import syntax for a file to be packaged separately as a chunk import with js code: WebpackChunkName: specifies the name of the separately packaged test file */ import(/* webpackChunkName: 'test' * '/ test'), then (({count} the mul,) = > {/ / file loading successful ~ / / eslint - disable - next - line console. The log (the mul (2, 5)); = > {}). The catch () / / eslint - disable - next - line console. The log (' file loading failure ~ '); });Copy the code

6.2.3 Lazy Loading/Preloading

Lazy loading: files are loaded when they need to be used (code splitting required). However, if the resource is large, the load time will be long and there will be latency.

2. Normal loading: It can be considered as parallel loading (loading multiple files at the same time) without order. Loading unnecessary resources first will waste time.

3. Prefetch (poor compatibility) : Prefetch is loaded before use. When all other resources are loaded and the browser is free, the resource is surreptitiously loaded. So it’s loaded when you use it, and it’s fast. So it’s better to add preloading to lazy loading.

Code:

Document.getelementbyid (' BTN ').onclick = function() { // webpackPrefetch: true to enable preloading import(/* webpackChunkName: 'test', webpackPrefetch: true */'./test').then(({ mul }) => { console.log(mul(4, 5)); }); import('./test').then(({ mul }) => { console.log(mul(2, 5)) }) };Copy the code

Reference code

Due to the author’s own ability priority, some parts of the description may be a little confusing.

You can refer to webpack-Study. It has all the code mentioned above and can be complex for everyone to understand.

Refer to the video

Silicon Valley 2020 latest version of Webpack5 combat tutorial (from beginner to master)