As a webpack small white, I have recently started to learn, but suffer from does not know how to learn, recently saw some explain webpack video still feel pretty good, at least for a beginner, I still think learned a lot, here is a recent watching video and learn some of the content, there is a problem meet you oh.

1. The webpack role

Core features of WebPack

Packaging.

What is packing

In short, packaging is to merge multiple files into a SINGLE JS file, that is, the process of merging after development is packaging.

Why use Webpack

When we were developing HTML pages, we manually imported multiple files we needed. If we packaged them into a single file, it would reduce the number of HTTP requests and make our pages load and display faster. Webpack also has many other features, such as opening local servers, updating while writing code, compression, etc. In short, it brings us a lot of convenient functions.

2. Common terminology for Webpack

Module

Modules, divided code units, modules in Webpack can be JS, CSS, LESS, TS, JSX and other static files, it can be said that one by one we handwritten files are modules, they are the unit of webpack file processing.

bundle

The bundle, which is generated by many different modules, can be understood as the final output file.

chunk

Chunk is a chunk file that Webpack generates based on the reference relationships in the file.

The hand-written file is Module, the reference file processed by Webpack is chunk, and the final output file is bundle.

5 core concepts of Webpack

The entrance (entry)

Entry, indicating which module webPack should use as the Entry to start packing, and establishing its internal dependency map. Entrances can be single or multiple.

Output (output)

Output indicates where and how to name multiple files merged into a bundle.

loader

Webpack can only understand JavaScript and JSON files, which is a built-in capability of WebPack available out of the box. Loader enables WebPack to process other types of files and convert them into valid modules for use by applications and to be added to dependency diagrams.

The procedure for using loader is 1. Download and 2. Use loader

Plug-in (plugins)

Plugins are used to transform certain types of modules, while plug-ins can be used to perform a wider range of tasks. Including: package optimization, resource management, injection of environment variables.

The steps of plugin use are 1. Download, 2. Import, 3

Mode (mode)

Mode includes development mode and production mode, which respectively provide the environment for developers to debug and the environment for code optimization to go online.

4 WebPack initialization

1. Generate package. Json

First create folder webpack-demo folder, run NPM init -y in webpack-demo directory to generate package.json configuration file

2. Install webpack webpack-CLI

Run NPM install webpack webpack-cli –save-dev to generate a node-modules folder

Note: the difference between -g -D -S in command line

-g –global is short for global installation of the module,-g installed module is the project of this computer can be used by -d –save-dev local installation of the module, local means only for the current project, is used in the development environment, is not used in production environment. The module writes to the devDependencies object in package.json.

The devDependencies object is a package that you use to package your code. It’s a package that you don’t need to package your code. It’s a package that you use to identify specific files and code and help you produce the final file.

The module is installed in the node_modules folder of the project folder

-s — short for save. Install modules globally, not only in development environments but also in production environments. Write modules to the Dependencies object of package.json.

The dependencies object, unlike The devDependencies object, needs to be published to the production environment. For example, if you run a vue-based project, you need vue.js to support it. NPM I VUE-s installs vUE modules into project dependencies and releases them to production.

The module is installed in the node_modules folder of the project folder

3. Create a configuration file

Create webpack.config.js in the root directory

When using this configuration file, execute the webpack command to perform the packaging, but there is a question is that the configuration file must be this, in fact, it is not, for example, I want to use xxx.js as the configuration file? We can specify the configuration file by running the command webpack –config xxx.js.

5 WebPack Development environment Configuration

Development environment configuration requires configuration file mode:’development’

1. The packaging of CSS

We know that Webpack can only understand JS and JSON files and cannot package CSS directly. In this case, we need to use CSS-loader, which is used to parse CSS and load CSS into JS.

  • Write file

  • Install the CSS – loader

npm i css-laoder -D

  • To configure the CSS – loader

  • The results of

You can see that index.css has been introduced

2. Pack less

CSS is first loaded by less-loader, converted to CSS, and then loaded into JS by CSS-loader

  • Write file

  • Install less less-loader CSS-loader

Less NPM I less-loader less CSS-loader-d must be installed at the same time

  • Configuration is less – loader CSS – loader

  • The results of

An error was reported after executing webpack

The installed version of less-loader is too high. The solution is as follows: 1. NPM uninstall less-loader [email protected]

Less is successfully packaged.

3. Packaging HTML

The htMl-webpack-plugin, by default, creates an empty HTML file and automatically imports all the output resources (JS/CSS). You can also create your own HTML file without the need for HTML import files, which will be automatically imported after using this plugin

  • Write file

  • Download the plugin package

npm install --save-dev html-webpack-plugin

  • The configuration file

  • The results of

NPM uninstall html-webpack-plugin. 2. NPM install I [email protected] -d

The final result

4. Display the CSS effect

Mian.js has been introduced into HTML through the above steps, but the CSS has not actually taken effect, that is, the STYLE of THE HTML has not been changed, because CSS is not actually applied to THE HTML, this time needs to use style-loader. Style-loader is used to mount the content parsed by CSS-Loader to the style tag and add the style tag to the HTML document.

  • Write file

Same as above

  • Download style – loader

npm i style-loader -D

  • The configuration file

  • The results of

You can see that the style is in effect.

4. Pack images

Image resources can be referenced in styles, such as background images, or directly used in HTML. File-loader or URl-loader can handle image resources. The difference between them is that url-loader can be set to Base64 when the image size is lower than a certain threshold. This reduces the number of requests, but by default they cannot process images in HTML, which can be imported by htMl-loader and thus processed by URL-loader. – Write files

  • Download url-loader, file-loader and html-loader
  • npm install --save-dev html-loader url-loader file-loader
  • The configuration file

As expected, the error was reported again, or the download version was too high, 1. NPM uninstall html-loader url-loader file-loader,2. NPM install [email protected] [email protected] [email protected] -d

5. Pack other resources

  • Importing additional files

  • The configuration file

Results –

6. devServer

DevServer takes effect only in the development environment. To make the configuration in derServe take effect, run the webpack-dev-server command. If the configuration is modified, run the command again.

  • devServer.open

When DevServer completes its first build, web pages are automatically opened with a browser, which defaults to True

  • devServer.hot

Enable webpack module hot replacement, after modifying the source code can see the effect of the update in real time in the browser

  • devServer.compress

Turn on gzip compression for each static file

  • devServer.contentBase

Post-project build path

  • devServer.port

Specified port number

  • devServer.proxy

Open the agent

6 WebPack Production Environment Configuration

Mode needs to be set to production in the production environment

1. Extract the CSS into a separate file

Mini-css-extract-plugin is needed. After csS-Loader processing, CSS files have been integrated into JS. What we need is to extract these CSS files into a separate CSS file. Ini-css-extract-plugin plugin is used to extract CSS from JS files into separate files

  • Write file

  • Download the plugin

NPM install - save - dev [email protected]

Note: Because many downloaded versions are too high, it will lead to errors when running Webpack, so the version number will be added directly after downloading

  • The configuration file

  • The results of

2. Check the CSS compatibility

CSS compatibility processing is mainly for CSS3 styles, preset operation, we need to download postCSs-loader postCSs-preset -env, and configure Browserslist in package.json, Postcss loads the specified CSS compatibility style by finding the configuration in package.json within Browserslist.

  • Write file

slightly

  • Download the loader

npm install --save-dev postcss-loader postcss-preset-env

  • The configuration file

  • Configure Browserslist in package.json

// Last 1 means compatible to the last version of "development": ["last 1 Chrome version", "last 1 Firefox version", "last 1 Safari version"], // Production environment: default is to look at the production environment "production": [">0.2 ", "not dead", "not op_mini all"]}Copy the code

3. Compress CSS

  • download

npm install --save-dev optimize-css-assets-webpack-plugin

  • The configuration file

4. Check the js syntax

Eslint-loader eslint eslint-config-airbnb-base eslint-plugin-import eslint-loader eslint-config-airbnb-base eslint-plugin-import eslint-loader eslint-config-import We only need to check the syntax of our hand-written JS files. Js files in node_modules do not need syntax checking, so we need to exclude this folder. We also need to configure eslintConfig in package.json for syntax checking according to this rule, and we are using the Airbnb specification, so eslint-config-Airbnb-base is also installed.

  • download

npm install --save-dev eslint-loader eslint eslint-config-airbnb-base eslint-plugin-import

  • The configuration file

  • Configuration package. Json
"eslintConfig": {
     "extends": "airbnb-base",
      "env": {
         "browser": true 
        }
  }
Copy the code

5. Js compressed

In production, just set mode: ‘production’ and js code will be compressed automatically

6. HTML compression

HTML compression uses the HTML-webpack-plugin

  • download

npm install --save-dev html-webpack-plugin

  • The configuration file

How to do, Friday, is writing my heart had flown away, but there are a lot of content did not write ah, no, I have to go off work, have time to update oh, see all look, don’t forget to give me a praise oh, thank the handsome boy beauty ha ha.

7. Webpack optimizes the environment configuration

1. HMR(Hot module replacement)

HMR functionality changes to a module and repackages only that module (rather than all modules), which can greatly speed up builds. Style files: HMR functionality can be used: because style-loader is implemented internally

Js files: The HMR function cannot be used by default. You need to modify the JS code to add codes that support the HMR function, and enable the HMR function only for non-entry files

HTML files: The HMR function is disabled by default, which causes problems: THE HTML file cannot be hot updated. The solution is to modify the entry entry and import the HTML file

2. source-map

Source-map is a technique that provides source-to-built code mapping, meaning that when enough code is built to go wrong, it can locate the source code that went wrong

[inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map

The meanings of the fields are as follows

Inline: Inline, does not generate a separate external file

Hidden: Don’t track source code errors

Eval: Each file generates an inline source-map

Nosources: No source code information

Cheap: The error message is accurate only to the line

Module: Module imports the Source map of the Loader

Source-map can be:

The source – the map: external

Error code exact information and source code error location

The inline – source – the map: inline

Only one inline source-map is generated

Error code exact information and source code error location

Hidden – source – the map: external

Error code error cause, but no error location

You cannot trace source code errors, only the error location of the built code

The eval – source – the map: inline

Each file generates a corresponding source-map, all in eval

Error code exact information and source code error location

Nosources – source – the map: external

Error code exact information, but no source code information

Being the source – the map: external

Error code exact information and source code error location

Only accurate lines

Being – the module – the source – the map: external

Error code exact information and source code error location

Module adds the Loader source map

The differences between inline and external are as follows: 1. Files are generated externally, but not inline. 2

Development environment: fast and debug friendly

Speed (eval > the inline > being >…).

eval-cheap-souce-map

eval-source-map

More debug friendly

souce-map

cheap-module-souce-map

cheap-souce-map

Production environment: Should source code be hidden? Debugging should be more friendly

Inlining makes code bigger, so it’s not used in production

Nosource-source-map Is hidden

Hidden-source-map only hides the source code, prompting post-build code error messages

3. oneOf

Webpack normally traverses all loaders in Rules, but generally only one file type is matched. Use oneOf to load the corresponding Loader according to the file type, and exit as long as one file type is matched. For files of the same type, such as js processing, if multiple Loaders are required, you can separate js processing, ensure that one file type in oneOf corresponds to one loader, and configure Enforce: ‘pre’ to specify the priority of execution

4. The cache

Caching typically involves enabling the Babel cache (which is time-consuming) and file resource cache

Babel cache: Makes the second packaged build faster

File resource cache: Three types of hashes are used in file resource cache

  • Hash: A unique hash value is generated for each Wepack build

Problem: Because JS and CSS use the same hash value. If repackaged, all caches will be invalidated. (Maybe I only changed one file)

  • Chunkhash: Hash value generated by chunk. If the package comes from the same chunk, the hash value is the same

Problem: JS and CSS have the same hash value because CSS is introduced in JS, so it belongs to the same chunk

  • Contenthash: Generates hash values based on file contents. Different files must have different hash values

5. tree shaking

Tree shaking is about removing unnecessary code and reducing the size of the code

Prerequisite for Trees Shaking: Production environment and ES6 modularity

Configure: package.json configure “sideEffects”: False, if all code is tree shaking, but there are some problems like tree shaking CSS / @babel/polyfill files as well. So we can configure “sideEffects” like this: [“*.css”, “*.less”], which tells webpack that only these files have sideEffects, and that all other files are tree-shaking, but keep these files

6. Code split

Code split splits a large JS file into several smaller js files for parallel loading, making it faster. For example, in a vUE single-page application, if no processing is done, all VUE files will be packaged into one file, which is very large, resulting in a slow entry of the web page for the first time. At this time, code segmentation can be used to improve the loading speed.

  • Code segmentation through multiple entry

  • Use Optimization to package common code separately

  • Import Dynamic import

7. Multi-process packaging

For large projects, multi-process packaging can be enabled through the Tread Loader, but for small projects, it is not necessary to enable multi-thread packaging, because the startup time of multi-thread packaging is about 600ms, which may take longer than before

8. externals

To prevent packages from being packed into our final bundle and getting too big

9. dll

Use DLL technology for some libraries (third-party libraries: jquery, React, vue…) For example, in general, the packages in node_modules will be packed into a chunk, but the third-party libraries are too large to be packed into a chunk file. Therefore, all libraries can be separately packed into different chunks through DLLS, which is more conducive to performance optimization and construction speed

  • Create a new webpack.dll.js file

  • Webpack file configuration

Lazy loading and preloading

  • Lazy loading: files are loaded when they are needed

  • Prefetch: Surreptitiously loads resources after other resources have loaded and the browser is free

Note: Poor compatibility, use with caution

On the basis of lazy loading, add webpackPrefetch:true set to preload

Ending 8.

Finally updated, if you see the help, welcome to click 👍 and attention oh, thank you