Jsliang job series – 31 – webpack

Time:2021-2-24

A catalogue

What’s the difference between the front end and salted fish

catalog
A catalogue
2. Foreword
What is webpack
Four core concepts of webpack
5. Webpack construction process
Six entry
Seven output
Eight loaders
8.1 common loaders for file processing
8.2 common loaders for syntax checking
8.3 common loaders for HTML code processing
8.4 common loaders for CSS code processing
8.5 common loaders for JS code processing
Nine plugins
9.1 common plugins
9.2 plugin for improving efficiency
The difference between loader and plugin
11. Resolve
Configure webpack from 0
12.1 technology selection
12.2 loader configuration – handling CSS and less
12.3 loader configuration – processing pictures
12.4 loader configuration – handling fonts
12.5 loader configuration – MPa multi page packaging general scheme
12.6 SourceMap
12.7 WebpackDevServer
12.8 Babel analysis
12.9 React
12.10 performance optimization
12.11 others
13. Knowledge supplement: lazy loading
13.1 code segmentation
13.2 implementation principle
13.3 Vue on demand loading
14. Knowledge supplement: Hot update
14.1 turn on hot update
14.2 principle of thermal renewal
Three kinds of hash
16. Knowledge supplement: source map
Seventeen knowledge supplement: webpack packaging principle
18 references
18.1 webpack series
18.2 webpack performance optimization
18.3 Scope Hoisting
18.4 Tree Shaking
18.5 lazy loading

2. Foreword

Return to directory

It’s 2020. It seems a bit unreasonable not to order webpack.

But in fact, if you are not assigned to a group such as architecture group, you will feel less likely to contact webpack.

It’s likejsliangIn the last company, I didn’t have the opportunity to contact webpack. I used the solution that others had already configured to do a business~

What is webpack

Return to directory

Webpack is a static module packer for modern JavaScript applications(module bundler)。

When webpack processes an application, it recursively builds a dependency graph(dependency graph), which contains each module the application needs, and then packages all of these modules into one or morebundle

Therefore, its essence is a module packer, and its job is to package each module into a corresponding modulebundle

Four core concepts of webpack

5. Webpack construction process

Return to directory

Webpack is like a production line. It needs to go through a series of processes before it can convert the source file into the output result.

The responsibility of each process in this production line is single, and there is a dependency relationship between multiple processes. Only after the current process is completed can it be handed over to the next process.

WebpackThe running process of is a serial process. From start to end, the following processes will be executed in turn:

  • Initialization parameters: from configuration file andShellStatement to read and merge parameters, get the final parameters
  • Start compiling: initialize with the parameters obtained in the previous stepCompilerObject, load all the configured plug-ins, execute therunMethod to start compilation
  • Identify the entrance: according to theentryFind all the entry files
  • Compile module: starting from the entry file, call all the configuredLoaderTranslate the module, find out the module that the module depends on, and then recurse this step until all the files that the entry depends on have been processed in this step
  • Complete the module compilation: use after step 4LoaderAfter translating all the modules, we get the final content of each module and the dependency relationship between them
  • Export resources: according to the dependency relationship between the entry and the module, assemble into a system that contains multiple modulesChunkAnd put eachChunkThis step is the last chance to modify the output
  • Output complete: after determining the output content, determine the output path and file name according to the configuration, and write the file content to the file system

In short:

  • initialization: start build, read and merge configuration parameters, loadPlugin, instantiateCompiler(hook)
  • compile: fromEntryLet’s go, for each oneModule(module) serial call correspondingLoaderTo translate the contents of the file, and then find the fileModuleDependentModuleTo compile recursively
  • output: the compiledModulemergeChunk, willChunkConvert to file, output to file system(ChunkIn the packaging process, the entry module refers to other modules, and then the module refers to the module, which is connected by the relationship chainModuleIt’s formedChunk

In the process,WebpackThe plug-in will broadcast specific events at a specific time point. After listening to the events of interest, the plug-in will execute specific logic, and the plug-in can callWebpackProvidedAPIchangeWebpackThe running results of the system.

Six entry

Return to directory

There are three different forms of specified packing port filestring | object | array

One to one: one entry, one package file

module.exports = {
  entry: './src/index.js'
}

Many to one: multiple entries, one package file

module.exports = {
  entry: [
    './src/index1.js',
    './src/index2.js',
  ]
}

Many to many: multiple entries, multiple packaged files

module.exports = {
  entry: {
    'index1': "./src/index1.js",
    'index2': "./src/index2.js"
  }
}

Seven output

Return to directory

The location of the packaged file.

module.exports = {
  ...,
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
    filename: "[name].js"
  }
}
  • You can specify a fixed file name, if it is multi entry and multi exit(entryObject), you can’t use single file exit, you need to use the following method
  • adoptWebpackBuilt in variable placeholder:[name]

Eight loaders

Return to directory

loaderThe execution order of is from right to left, that is, the followingloaderDo it first.

If configured:

// webpack.config.js
module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.(le|c)ss$/,
        use: ['style-loader', 'css-loader', 'less-loader'],
        exclude: /node_modules/,
      },
    ],
  },
};

That is to deal with it firstless-loaderAnd then deal with itcss-loaderThe final treatmentstyle-loader

8.1 common loaders for file processing

8.2 common loaders for syntax checking

Return to directory

  • tslint-loader: checking typescript code through tslint
  • eslint-loader: checking JavaScript code through eslint

8.3 common loaders for HTML code processing

Return to directory

  • html-withimg-loader: processing images in HTML

8.4 common loaders for CSS code processing

8.5 common loaders for JS code processing

Return to directory

  • babel-loader: to convert JS code to a lower version, we need to usebabel-loader
  • ts-loader: convert typescript to JavaScript

Nine plugins

Return to directory

9.1 common plugins

Return to directory

  • clean-webpack-plugin: automatic cleaning before packingdistDirectory to prevent file residue.
  • copy-webpack-plugin: copy a single file or entire directory to the build directory
  • mini-css-extract-plugin: separate CSS and package it separately, and you can set whether to compress it by configuration.
  • html-webpack-plugin: this plug-in can be configured to generate an HTML5 file, wherescriptThe tag contains all webpack packages. If you set up multiple entry points, you can package multi page applications accordingly.

9.2 plugin for improving efficiency

Return to directory

  • webpack-dashboard: can be more friendly display of packaging information.
  • webpack-merge: extract public configuration to reduce duplicate configuration code
  • speed-measure-webpack-pluginSMP, for short, analyzes the time-consuming of loader and plug in in the process of webpack packaging, which helps to find the performance bottleneck in the construction process.
  • size-plugin: monitor the change of resource volume to find problems as early as possible
  • HotModuleReplacementPlugin: module hot swap

The difference between loader and plugin

Return to directory

  • Loader

LoaderIn essence, it is a function that converts the received content and returns the converted result.

becauseWebpackI only know JavaScript, soLoaderIt becomes a translator, dealing with different types of resources.

It’s likefile-loaderperhapsurl-loaderAfter configuration, it can be referenced correctlypngAnd so ontxtAnd so on.

It’s likestyle-loaderas well ascss-loaderAfter reference, you can precompile the CSS content.

  • Plugin

PluginIt’s plug-ins. It’s like plug-insjsliangThe vs code plug-in is the same,PluginExpandedWebpackThe function of.

PluginThat’s rightWebpackIn order to achieve the user’s purpose.

It’s likehtml-webpack-pluginWith the use of multi entry form, we can realize the function of multi page application.

It’s likeclean-webpack-pluginEmpty before packagingdistcatalog,copy-webpack-pluginYou can copy a single file or an entire directory to the build directory.

11. Resolve

Return to directory

resolveConfigure webpack how to find the file corresponding to the module.

Webpack has built-in JavaScript modular syntax parsing function. By default, it will use the agreed rules in the modular standard to find, but you can modify the default rules according to your own needs.

// webpack.config.js
module.exports = {
  //....
  resolve: {
    modules: ['./src/components', 'node_ Modules'] // search from left to right
  }
}
  • resolve.modules: to configure webpack to search for third-party modules in which directories. By default, it will only search for third-party modulesnode_modulesIf the module under a folder in the project is often imported and you don’t want to write a long path, you can configure itresolve.modulesTo simplify.
  • resolve.alias: the configuration item maps the original import path to a new one by alias.
  • resolve.extensions: in the project of adapting to multi terminal, there may be some problems.web.js, .wx.jsFor example, in the project of transferring to the web, we want to find the.web.jsIf not, look again.jsextensions: ['web.js', '.js']

Configure webpack from 0

Return to directory

How to configure a webpack scaffold from 0? That involves the selection of models.

12.1 technology selection

Return to directory

  • Mobile terminal PC
  • MPA || SPA
  • HTML | template engine
  • CSS | preprocessor
  • JavaScript ES5 || ES6
  • Local publishing service (data simulation)
  • React || Vue
  • Multi player project | single player project
  • Grammar specification eslint
  • unit testing
  • Submission specification

12.2 loader configuration – handling CSS and less

Return to directory

  • use: ['style-loader', 'css-loader', 'postcss-loader', 'less-loader']
  • less less-loader: analysis.lessfile
  • postcss-loader autoprefixer: YesflexLayout, etc

12.3 loader configuration – processing pictures

12.4 loader configuration – handling fonts

Return to directory

  • url-loader

12.5 loader configuration – MPa multi page packaging general scheme

Return to directory

  • installglob
  • takeentryandhtmlwebpackpluginDynamic generation

12.6 SourceMap

Return to directory

  • Development environment configuration:devtool: "cheap-module-eval-source-map
  • Online build configuration (not recommended)devtool: "cheap-module-source-map"

12.7 WebpackDevServer

Return to directory

  • install
  • to configure:devServer
  • HMR(hot module replacement)
  • Open JS moduleHMR, needWebpackcoordination

12.8 Babel analysis

Return to directory

  • Installation:npm i babel-loader @babel/core @babel-preset-env -D

    • @babel/corebabelcore
    • babel-loaderbabelandWebpackThe bridge connecting the two sides
    • babel-preset-env: output what kind of code, use it to solve
  • babel-loader: analysis of ES6+
  • @babel/polyfill: gasket. Contains all ES6 + new feature codes
  • .babelrc

12.9 React

Return to directory

  • Installation:react react-dom
  • use:@babel/preset-react

12.10 performance optimization

Return to directory

  • narrowloaderScope of documents:loaderOfincludeConfiguration, which can be specifiedsrcDirectory, reduce the scope of inspection.
  • optimizationresolve.modulesConfiguration: ConfigurationWebpackWhich directory to search for the third-party module, the defaultnode_modules
  • Separate CSS:MiniCssExtractPlugin
  • hashchunkhashcontenthashdifference

    • hashScope JS, CSS, imagehashThere’s a difference. Every time you package a build, it changes.
    • chunkhashwithchunkIf you change that part, you can change which parthash. (the dependent modules also changehash
    • contenthashOnly when one’s own content changes can one change (different fromchunkhash
    • So JS applies tochunkhash; CSS forcontenthash; image forhash
  • Compress CSS:optimize-css-assets-webpack-pluginandcssnano
  • Compressed HTML:html-webpack-plugin
  • Compressed image:img-webpack-loader
  • separateWebpackConfiguration: separationbase.configdev.configmpa.configandpro.configFour, yesmergeconductconfigConfiguration merging

See more here:

Webpack performance optimization

12.11 others

Return to directory

  • How to write a simpleWebpackParser
  • How to write aWebpack loader
  • How to write aWebpack plugin

13. Knowledge supplement: lazy loading

Return to directory

Lazy loading or on-demand loading is a good way to optimize web pages or applications.

In fact, this way is to separate your code from some logical breakpoints, and then refer to or about to refer to some new code blocks immediately after some operations are completed in some code blocks.

This speeds up the initial loading of the application and reduces its overall size, because some code blocks may never be loaded.

13.1 code segmentation

Return to directory

Code segmentation(code splitting)It refers to the process of converting the code that does not need to be called immediately in the script into asynchronous loading during code construction.

During the construction of webpack, the code declared to be loaded asynchronously will be avoided. The asynchronous code will be separated into a single file and loaded into the page when the code is actually called.

The core of code segmentation technology isLoading resources asynchronously

Fortunately, the browser allows us to do so, W3Cstage 3standard:whatwg/loaderIt’s defined: you canimport()Keyword allows the browser to load related resources asynchronously during program execution.

In Vue, you can use theimport()Keywords do this, and in react, you need to usereact-loadableTo do the same thing.

13.2 implementation principle

Return to directory

  1. Package the sub modules that need to be loaded lazily into files(children chunk
  2. With the help of function to delay the sub module loading code(import

print.js

console.log ('output 1 ');

export default () => {
  console.log ('output 2 ');
};

index.js

const btn = document.querySelector('.btn');
btn.onclick = import('./print.js').then((module) => {
  const print = module.default;
  print();
});

13.3 Vue on demand loading

Return to directory

Vue is characterized by Spa – single page application.

Only the first time to load the page, after each page switch, only need to replace the component.

It reduces the number of requests, speeds up page response, reduces the pressure on the server, and so on.

However, because Vue is a spa, all components and their related resources will be loaded when the home page is loaded for the first time, which will slow down the opening speed of the home page and reduce the user experience.

In Vue project, webpack can be combined tovue-routeradoptimportDynamic loading:

const routes = [{
  path: '/',
  name: 'Home',
  component: () => import('../views/Home.vue')
}];

14. Knowledge supplement: Hot update

Return to directory

Refresh is generally divided into two types:

  • One is the page refresh, does not retain the page state, is simple and crude, directwindow.location.reload()
  • The other is based onWDSWebpack-dev-server)Module hot replacement of, only need to refresh the changed module on the page, at the same time can retain the current page state, such as the check box selected state, input box input and so on.

WebpackHot replacement is also called hot replacement(Hot Module Replacement), abbreviated asHMR

This mechanism can replace the old module with the new one without refreshing the browser.

14.1 turn on hot update

Return to directory

In webpackwebpack.config.jsMedium:

  1. to configuredevServerOfhotbytrue
  2. staypluginsMedium increasenew webpack.HotModuleReplacementPlugin()
// webpack.config.js
const webpack = require('webpack');
module.exports = {
  //....
  devServer: {
    hot: true
  },
  plugins: [
    new  webpack.HotModuleReplacementPlugin () // hot update plug in
  ]
}

And in the entry file configuration:

if(module && module.hot) {
  module.hot.accept()
}

At this point, when modifying the code, only the corresponding part of the content will be updated accordingly.

14.2 principle of thermal renewal

Return to directory

HMRThe core of the client is to pull the updated file from the serverchunk diffchunkParts that need to be updated).

actuallywebpack-dev-serverWDS)And the browser maintains aWebsocketWhen the local resource changes,WDSUpdates are pushed to the browser with the build time updatehashTo compare the client with the last resource.

After comparing the differences, the client will send theWDSlaunchAjaxRequest to get the changes (file listhash)In this way, the client can continue to send theWDSlaunchjsonpRequest to get thechunkIncremental update of.

How to deal with the subsequent part (after getting the incremental update? Which states should be retained? What needs to be updated?) fromHotModulePluginTo complete, provides the relevant informationAPIFor developers to deal with their own scenarios, such asreact-hot-loaderandvue-loaderIt’s all with theseAPIrealizationHMR

Three kinds of hash

Return to directory

File fingerprint is the suffix of the output file name after packaging, corresponding to three typeshash

  • hashIt is related to the construction of the whole project. As long as there are file changes in the project, the whole project will be builthashValues change, and all files share the samehashValue. (whole project)
  • chunkhashIt parses the dependent files according to different entries and builds the correspondingchunk(module) to generate the correspondinghashValue. Only modifiedchunk(modules) are not generated until they are rebuilthashValue, will not affect the otherschunk. (particle size)entry(for each entry file)
  • contenthashIt is related to each generated file, and each file has a uniquehashValue. When the content of the file to be built changes, a new file is generatedhashAnd the change of this file will not affect other files in the same module. (granularity the content of each file)

16. Knowledge supplement: source map

Return to directory

source mapIt is the process of mapping the compiled, packaged and compressed code back to the source code. The packed and compressed code does not have good readability, so you need to debug the source codesoucre map

mapThe browser will not load the file as long as the developer tool is not opened.

There are three solutions for online environment

  • hidden-source-map: with the help of the third party error monitoring platformSentryuse
  • nosources-source-map: only the specific number of lines and the error stack of the source code will be displayed. Safety ratiosource maphigh
  • source map: bynginxSetting will.mapDocuments are only open to whitelist (company intranet)

Note: avoid use in productioninline-andeval-Because they increasebundleVolume size, and reduces overall performance.

Seventeen knowledge supplement: webpack packaging principle

Return to directory

In the simple implementation of webpack, how to package a piece of code is simple

  1. utilizebabelComplete the code conversion and generate the dependency of a single file
  2. Generation dependency map
  3. Generate final packaging code

18 references

Return to directory

There are 51 references in this series.

18.1 webpack series

Return to directory

other

Articles in 2020

Articles in 2019

Articles in 2018

2017 article

18.2 webpack performance optimization

Return to directory

Articles in 2019

Articles in 2018

Articles in 2017

18.3 Scope Hoisting

Return to directory

18.4 Tree Shaking

Return to directory

18.5 lazy loading

Return to directory


Jsliang’s document library consists ofLiang JunronguseCreative Commons Attribution – non commercial use – same way sharing 4.0 international license agreementPermission. < br / > based onhttps://github.com/LiangJunrong/document-libraryThe creation of works on the Internet. < br / > the use rights other than those authorized in this license agreement can be obtained fromhttps://creativecommons.org/licenses/by-nc-sa/2.5/cn/It’s available from.