Webpack optimization direction

Optimization for WebPack is generally considered in terms of development experience and output code quality

(I) Optimize the development experience

It is usually optimized for build speed and use experience

[Development environment]

  1. Narrow the search scope of files (loader configures include\exclude, module.noParse to ignore recursive parsing of files that do not use some modules, resolve modules directly specify the path of third-party modules)
  2. ** Refresh automatically **(Set watch:true, but refresh the browser by braking)
  3. Hot update (no page refresh, status will not be lost module.hot)
  4. ** DllPlugin** (package as a dynamically linked library for dependent third-party libraries)

[Production environment]

  1. Optimization of able-loader (enable caching)
  2. IgnorePlugin
  3. noParse
  4. HappyPack (Multi-threaded packaging)
  5. ParallelUglifyPlugin (Multi-threaded packaging)

(2) Optimize the output quality

[Reduce the load time perceived by the user, that is, the first screen load time]

  1. To distinguish the environment
  2. Compressed code (JS CSS image)
  3. **tree-shaking ** (Remove code not used)
  4. Extract common code (multithreaded packaging)
  5. Split code loaded on demand (multi-threaded packaging)
  6. The CDN to accelerate

Improve fluency, that is, improve code performance

  1. Scope Hosting(Make file packaging smaller and run faster)
  2. Prepack (Compiling code is to place the calculated results in the compiled code ahead of time and run the output directly)

Analysis of correlation principle


Automatically refresh

To turn WebPack on file listening mode, simply set wacth: true,wacthOptions to not listen to files

Principle of File monitoring

  1. The principle of file listening is to periodically obtain the last editing time of a file. Each time, the latest editing time is saved. If the current editing time is inconsistent with the last editing time saved, the file is considered to have changed
  2. For multiple files, WebPack starts from the entry file, recurses all dependency files, and adds them to the listener list
  3. Save the file and the last edit time take up memory, reduce the number of listening files and reduce detection frequency

Principle of automatic refresh

  1. Use browser extensions to refresh through the interface provided by the browser
  2. Injection of proxy client code to the development of web pages, through the proxy client to refresh the page

Hot update

advantage

  1. Real-time preview
  2. You can keep the running state of the current web page without refreshing the browser

The principle of

  1. Inject a proxy client into the project to connect DevServer to the project
  2. Every time DevServer changes a file, it generates a hotupdate.js patch file to replace the old template, and browser developer tools can also see the request for the patch pack
  3. However, when editing main.js, you will find that the entire page is refreshed. The reason is that when the sub-module is updated, the update event will be passed up one layer, until the outermost layer has no file to receive it, and the page will be refreshed
  4. There is no place to receive CSS files, but modifying all CSS files will trigger hot updates because style-loader will inject the code to receive CSS

DllPlugin

For the dependent third-party libraries, such as Vue and Vuex, which will not be modified, we can package them separately from our own code. The advantage of this is that every time I change the file of my local code, WebPack only needs to package the file code of my project, instead of compiling the third-party library. So the third party library is only packaged once when it is packaged for the first time. In the future, webPack will not package these libraries as long as we do not upgrade the third party package, which can quickly improve the packaging speed

  1. The base modules that the project depends on are separated and packaged into separate dynamically linked libraries
  2. If a module to be imported exists in a dynamic link library, the module cannot be packaged and can be directly obtained from the dynamic link library
  3. All dynamically linked libraries that the project depends on need to be loaded

bable-loader

  1. The function is to recognize es6+ syntax
  2. The AST is then iterated through the JS lexical parser to generate a new AST from the EStree specification, and the ES5 code is then transformed through the generator
  3. Part of the new prototype method (Peoxy, SET) Babel is not translatable to the need to introduce polyfil solutions
  4. CacheDirectory, which enables caching to avoid the high-performance Bable recompilation process that can occur with each subsequent execution

HappyPack (multi-process build to reduce total build time)

There is another layer between Webpack and Loader. When Webpack needs to compile a resource module of a certain type, HappyPack assigns the resource task to HappyPack, which schedules the task in its internal thread pool and assigns a thread to call the loader that processes the resource

  1. Rules, use[‘happyPack/loader? Id = CSS ‘]
  2. You can also configure new HappyPack({id: CSS}) in plugins, where the id identifies the file type
  3. The default process is 3, threads can be set

webpack-parallel-uglify-plugin

Parallel processing of multiple sub-tasks, after the completion of multiple sub-tasks, and then send the results to the main process, will open multiple sub-processes, for multiple JS file compression work under the direction of multiple sub-processes to complete, can delete all the comments, console.log, extract multiple times, but not defined as a variable of the application static value

  1. UglifyJS principle, parsing code into AST syntax tree, and then using a variety of rules to deal with it
  2. In Pulfgins, new a parallel uglify, uglifyJS configuration output compact, and remove all comments, compress removes console.log once used variables, etc

Tree-shaking

In essence, it eliminates unnecessary code in the project. By shaking out unused modules, it is called DCE, to achieve the purpose of removing unnecessary code, relying on the module features of ES6

DCE

  1. dead code eliminatiom
  2. Code will not be executed, not reachable
  3. The results of code execution are not used
  4. Code only affects variables (write, not read)

ES6 module features

  1. Can only be expected as the top level of a module
  2. The module name for import must be a string constant
  3. The introduction of modules is statically analyzed, so you can determine what code is loaded at compile time, analyze the program flow, determine which variables are used and referenced, and remove the code

disadvantages

  1. This only applies to ES6+ modularity syntax. To disable Babel module conversion in babelrc
  2. Js file, import a resource, and then the function is not used, import is not removed

Extract common code

  1. Cause: The same resource is repeatedly loaded, which wastes user traffic and server cost. The resource attitude leads to the slow first loading screen
  2. Benefits: Reduced network traffic and reduced server costs

How to extract the

  1. All the pages need to use the base library, extracted into a separate base.js file (long cache, static file name will be attached to the file content calculation of the Hash value, usually not)
  2. Find the code for the common parts that all pages depend on and extract it into common.js
  3. Generate a separate file for each page, do not contain the above part, each page needs separate part of the code
  4. The commonschunkPlugin is built into Webpack

Lazy loading (load on demand)

  1. Divide the entire site into small features
  2. Each class is merged into a chunk and the corresponding chunk is loaded on demand
  3. When users who do not need loading open the website for the first time, they need to see the corresponding function of the screen, which is placed in the chunk where the execution entrance is located to reduce the user perception of the loading time of the web page
  4. let TaskBtn = () => import(/ webpackChunkName: ‘task-btn’ / ‘@/components/TaskBtn.vue’);

Open the Scope Hoisting

Make webPack’s code file smaller and faster

  1. The code is smaller, and function declarations generate a lot of code
  2. The code creates fewer functions at run time with less scope and memory overhead
  3. Principle: Analyze the dependencies between modules and merge the scattered modules into a function as far as possible, but on the premise that there is no redundant code, only the modules referenced once can be merged

The CDN to accelerate

  1. Content distribution, speed up network transmission, speed up resource acquisition
  2. The file name of a static resource must have a Hash value calculated from the file content to prevent it from being cached
  3. Different types of resources are stored in different domain name CDN services to prevent blocking of concurrent loading of resources