Are you still worried about how to learn Webpack? Are you still worried about too many concepts? Welcome to see this sharing

Brief Introduction to share content:
  1. What is Webpack (Introduction to WebPack, WebPack workflow)
  2. What is chunk (concepts related to chunk, use of splitChunks plug-in)
  3. Webpack package optimization solution (common optimization plug-in & packaging optimization solution)
  4. Related content extensions (Webpack V3 V4 differences, hash, scripts configuration, PATH related concepts, etc.)

What is a webpack?

Front-end page effect is more and more cool, more and more complex functions and front-end engineers in order to more convenient development and improve the development efficiency of a series of DE exploration modular ideas put forward to divide complex programs into smaller files

React Vue Angular ES6 less Sass CSS processor, etc

All things are double-sided advantages and disadvantages greatly improve the development efficiency at the same time for the later maintenance caused trouble because the use of these tools of the file is often not directly recognized by the browser need to be manual processing very affect the development progress and in this environment background Webpack produced……

Let’s take a look at the official brochure

Webpack can be thought of as a module packer, and its main job is to parse your code structure and find javascript modules and other extension languages that browsers don’t recognize directly (SCSS, ES6, etc.) and convert and package them into appropriate formats for browsers to use

What exactly does WebPack do for us

It can be roughly divided into the following four categories:

  1. Common code is removed from unused code and is not packaged to reduce the total amount of code
  2. Babel-loader, sass-loader and so on to deal with the browser can not directly recognize the language to improve the development efficiency
  3. The WebPack-Server development mode optimizes the development process and reduces the workload
  4. File obfuscation compression reduces page rendering time and improves system security

Are there any specific changes before and after use? Let’s look at some examples and scenarios in detail below

Before using After using
The code is too redundant and difficult to maintain Create diagrams based on entry files and ignore useless code
Multiple requests for the same file Waste serious Slow page loading speed Poor user experience Remove the public chunk to avoid repeated references
Development changes to the file browser did not take effect because they preferentially read the cache Use hash names to avoid browser cache impact
Code comment removal cumbersome system security is not guaranteed Plugin to clear annotation encryption compression confusion in one step
In development mode, you need to go back to the browser frequently to refresh the browser to check the effect. The development efficiency is low HMR Hot update Dynamically updates views to avoid tedious operations
Various development technology tools have high technical requirements for developers Rich plug-in, loader automatic compilation to reduce the difficulty of development

It’s amazing to hear that WebPack has all these advantages because of its design philosophy and if you look at how it works, you’ll get a sense of how it works

Webpack builds a dependency graph recursively from the entry file. All file contents involved will be encapsulated by Webpack as independent module functions. Module functions will be packaged into chunk by chunk according to the configuration file we set. Finally, it is injected into the corresponding template view file in the form of a script tag, which is our common HTML file and manages the loading and running of the file by relying on the manifest file generated in the first step

What we can control and configure is generally the second and third steps and let’s look at that in detail

The main focus of this share is to learn some understanding of chunk and some custom build configurations

What is the chunk?

Chunk can be simply understood as a collection of module functions, namely, “code blocks”. By using Webpack processing, multiple entry files, public reference files, asynchronous loading files in the code can be separated into separate individuals, that is, each file generated after we pack. We can use chunk to improve packaging efficiency, save loading time, make more reasonable use of browser cache, etc..

The shared code uses WebPack V4

Four demos were used to simulate four cases of packaging processing

  • Single entry static file
  • Single entry public file
  • Single-entry asynchronous file loading
  • Multientry file

Document reference diagram:

Tip: And just to make it easier for you to understand, The code uses a very basic code structure and you can see in the demo that webPack is a common plug-in package Clean-webpack-plugin, html-webpack-plugin, webpack-merge, node environment global variable process.env, etc

We’ll notice that WebPack V4 has already broken up our code to a certain extent by default. The packing rules are as follows:

  1. Chunk and contains modules from the node_modules folder
  2. Not less than 30KB before compression
  3. The number of concurrent requests to be loaded on demand is not greater than 5
  4. The number of initial load concurrent requests is not greater than 3

The biggest change in WebPack V3 V4 is splitChunksPlugin instead of commonChunksPlugin

module.exports = { //... Optimization: {splitChunks: {chunks: "async", / / which the chunk can choose to optimize (all | async | initial) minSize: // Minimum size of chunks to be generated (b) minChunks: 1, // Minimum number of references to modules that must be shared before fragmentation maxAsyncRequests: 5, // Maximum number of parallel requests to be loaded as needed maxInitialRequests: 3, // Initialize the maximum number of parallel requests on the page automaticNameDelimiter: '~', // The general name of the chunk is in the format (vendors~main.js, for example) and the field indicates the separator name:true, // Name of chunk (trueCacheGroups: {// cacheGroups can inherit and override splitChunks.* all attributes, vendors: {test: /[\\/]node_modules[\\/]/, //testPriority: -10 //priority: priority only works in cache groups (default group priority is negative)}, default: {minChunks: 2, priority: -20, reuseExistingChunk:true, //reuseExistingChunk property only in the cache group operation whether to use the existing chunk if the condition of the chunk already exists no new chunk will be created filename:'[name].bundle.js'// Package the generated file name}}}}};Copy the code

The above configuration can be tested using the code case oh ~ here

So if you’re like me and you’re not familiar with rule 3 and rule 4 of the default, the parallel requests on demand and the initial concurrent requests correspond to maxAsyncRequest and maxInitialREquests, respectively, and these two attributes are designed to solve the problem of too much refinement in packaging If the number of chunks we end up with exceeds the maximum number we set, Webpack will merge the chunks to the maximum if it’s not clear Just look at the number of page scripts requests and set the maximum value

Webpack package optimization solution

  1. Reduce packaging time (remove common library files) :DllPlugin&DllReferencePlugin case
  2. Visualization tools:webpack-bundle-analyzer case
  3. Webpack plugin time viewing tool:speed-measure-webpack-plugin case
  4. Try using the DllPlugin&DllReferencePlugin and you will find that you cannot dynamically add vendor.dll.js files and you cannot add hash valueshtml-webpack-include-assets-plugin case

Related knowledge development

What are the differences in Webpack V3 V4?

The v4 mode keyword has two options: development and production. The default is production. As mentioned above, the new default packaging rule in development mode is added. NamedChunksPlugin and NamedModulesPlugin are enabled by default for easy debugging, providing more complete error messages and faster recompilation.

In production mode, the code will be automatically divided, compressed, and optimized with minimal configuration due to splitChunks and disarrays, and the Webpack will also help you Scope and tree-shaking automatically.

The implementation principle of Scope is actually very simple: analyze the dependency relationship between modules and combine the scattered modules into a function as much as possible, but on the premise that code redundancy cannot be caused.

Tree-shaking is all about eliminating useless JS code. Garbage elimination, which is widespread in traditional programming language compilers, allows the compiler to determine that some code does not affect the output at all and then eliminate it

More of the v3 v4 differences can be seen here: hand to hand, which takes you to use webpack4 in a reasonable posture

A link to the

  • How to configure scripts in package.json? NPM Scripts Usage Guide
  • Node & Webpack global variable configuration: cross-env
  • Node path.resolve path.join Difference: PATH join and resolve

(๑•̀ㅂ•́)و✧ for detailed information, visit Demo & PPT or Webpack Chunk by 4GVj

Thanks!

The original link: tech.meicai.cn/detail/98, you can also search the small program “Mei CAI product technical team” on wechat, full of dry goods and updated every week, want to learn technology you do not miss oh.