Webpack source flow

Zhaoguang 2021-02-23 16:12:18
webpack source flow

webpack It's a static module packaging tool . When webpack When processing an application , It recursively builds a dependency graph , It contains every module the application needs , Then package these modules into one or more bundle.

Some of the core options:

  • entry entrance
  • output
  • loader
  • plugin plug-in unit
  • mode Packaging mode

webpack Implementation process reference

Overall process

Integrate option(config + shell config) --> addEntry --> addModuleChain & addModuleDependcies --> buildModule --> seal Deal with each one chunk, Merge 、 Split 、 Generate hash --> createAssets & outputAssets --> end

Key event nodes

  • entryOption stay entry After the configuration item has been processed , perform
  • watchRun In monitor mode , A new compilation (compilation) After the trigger , Execute a plug-in
  • build-module , Mainly called loader Processing source files , Generate AST, Traverse AST, encounter require\import Such dependence , Create a dependency and add it to the dependency array
  • after-compile This is in seal Stage , For each module and chunk To organize , Generate compiled source code , Merge , Split , Generate hash.
  • emit event Generate resources to output Before the catalog .
  • after-emit Generate resources to output After the catalog .

Here are a few concepts that need to be clarified :

  • compiler And compilation The difference between objects

    • compiler On behalf of the entire webpack Life cycle from Startup to shutdown
    • compilation Object represents a new compilation modules become chunks Compilation process .(modules All parsed modules are recorded ; chunks It records everything chunk; assets All the files to be generated are recorded )
  • Tapable class

Mainly controls the publication and subscription of hook functions ( Observer mode ), Controls the webpack The plug-in system ,compiler & compilation Inherit from Tapaple . Tapable Libraries expose a lot of different types of hook

const {
} = require("tapable");
 Copy code 

Hook Class :

  • tap(name, fn): Register callback function fn, Just the current fn The code is finished ,Hook The next one will be executed fn;
  • tapAsync(name, fn, callback): Register callback functions with asynchronous operations , By calling the input parameter callback() inform Hook At present fn Execution completed , You can execute the next fn;
  • call(...args): according to Hook All callback functions are executed according to the corresponding rules ;
  • Async: Supports asynchronous operations in callback functions , It doesn't refer to the execution rules of the callback function ;
  • Series: Indicates that the execution rule of the callback function is serial , Empathy Parallel According to the parallel ;

therefore AsyncSeriesHook, Supports asynchronous operations in callback functions , And all registered callback functions are executed serially ;

compiler The event hook of the whole process is based on tapable Of hook Of

class Compiler extends Tapable {
this.hooks = {
beforeCompile: new AsyncSeriesHook(),
compile: new SyncHook(['params']),
afterCompile: xxx,
enterOption: xxx,
// ... Many types of hooks are defined
 Copy code 

With tapable Of syncHook Simple display , Here's a typical observer pattern

class SyncHook {
this.hooks = []
// subscribe
tap(name, fn){
// Release
this.hooks.forEach(hook => hook(...arguments))
const hooks1 = new SyncHook()
hooks1.tap('hook1', ()=>{})
hooks1.tap('hook2', ()=>{})
// Synchronous execution
 Copy code 

Then refer to the plug-in writing , You can understand compiler.hooks.enterOption.tab 了 .

Help us in different modes , Plug in introduced

common problem :

1、 How does the packaging process relate to plug-ins ? technological process +tapable.

Briefly describe the process +tapable

2、 Package optimization ?

got it , Let's talk about packaging optimization , It's clearer

  • 1、 Narrow file search

Make good use of rules Under the exclude, You don't need to babel-loader Documents processed ;

rules: [{
test: /\.js$/,
use: {
loader: 'babel-loader'
// exclude: /node_modules/,
include: [path.resolve(__dirname, 'src')]
 Copy code 

Third party libraries for references (jq,chartjs), No parsing and conversion .

 module: {
//noParse: /jquery|lodash|chartjs/,
noParse: function(content){
return /jquery|lodash|chartjs/.test(content)
 Copy code 

names alias , image @ @utils etc.

resolve.modules tell webpack Find references , Reduce business side ../../xx Use . such as :path.resolve(__dirname, "src")

utilize extensions The field tells webpack, The import module , Automatically bring in the suffix to try to match the corresponding file , Reduce traversal . It's best to import files in code , Try to put a suffix on it , Avoid finding .

 resolve: {
extensions: ['.js', '.json']
 Copy code 
  • 2、 Reduce packaging files

1、 Advance public code webpack 3 With CommonsChunkPlugin,webpack 4 With SplitChunksPlugin

2、 Make good use of tree-shaking, Remove useless code . It's all written in import xx from , modify babel Of preset( By default, any module type is compiled to Commonjs)

3、 Third party library leads to cdn Image formation vue、common、 Business js.

4、 Use the third-party library to find that kind of ES Module version of , Good for tree-shaking

  • 3、 cache

cache-loader Conduct loader The cache of

test: /\.js/,
use: [
loader: 'cache-loader'
loader: "babel-loader",
test: /\.js/,
use: [
loader: "babel-loader",
options: {
cacheDirectory: true
 Copy code 

HardSourceWebpackPlugin It can also provide caching function for modules .

plugins: [
new HardSourceWebpackPlugin()
 Copy code 
  • 4、 Multi process

thread-loader happypack Realize multi process processing , The actual effect is not obvious .

3、webpack5 What's new ?

  • 1、 Persistent cache 、 Long term cache , Improve build performance .
  • 2、 Better tree-shaking, Reduce volume .
  • 3、 No more for Node.js modular Auto reference Polyfills, Reduce the volume .

Learning links :



mini-pack Simplify the example



  1. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  2. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  3. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  4. 前端面试常考题:JS垃圾回收机制
  5. Frequently asked questions in front end interview: JS garbage collection mechanism
  6. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  7. Java之HTTP网络编程(一):TCP/SSL网页下载
  8. HTTP network programming in Java (1): TCP / SSL web page download
  9. Java之HTTP网络编程(一):TCP/SSL网页下载
  10. HTTP network programming in Java (1): TCP / SSL web page download
  11. 使用vite搭建vue项目
  12. 在组件中展示pdf文件:vue-pdf (由于未找到方法滑动加载下一页,只能点击加载下一页pdf文件)
  13. 在 vue 中通过 express 连接数据库
  14. Using vite to build Vue project
  15. Display PDF file in component: Vue pdf
  16. Connecting database through express in Vue
  17. 2021届秋招哈啰出行前端面经(一面)
  18. vue使用sdk进行七牛云上传
  19. Javascript性能优化【内联缓存】 V8引擎特性
  20. Small true wireless smart headset evaluation: put intelligence into the ear
  21. The front end experience of the 2021 autumn recruitment
  22. Vue uses SDK to upload Qi Niu cloud
  23. 深入理解 Web 协议 (三):HTTP 2
  24. dhtmlxGantt如何重新排序任务
  25. JavaScript performance optimization [inline cache] V8 engine features
  26. 深入理解 Web 协议 (三):HTTP 2
  27. Deep understanding of Web protocol (3): http 2
  28. 深入理解 Web 协议 (三):HTTP 2
  29. How dhtmlxgantt reorders tasks
  30. 深入理解 Web 协议 (三):HTTP 2
  31. JavaScriptBOM操作
  32. JavaScriptBOM操作
  33. Deep understanding of Web protocol (3): http 2
  34. Deep understanding of Web protocol (3): http 2
  35. dhtmlxGantt甘特图重新排序任视频教程
  36. vue实现七牛云上传图片功能
  37. vue.js环境配置步骤及npm run dev报错解决方案
  38. Deep understanding of Web protocol (3): http 2
  39. JavaScript BOM operation
  40. JavaScript BOM operation
  41. Dhtmlxgantt reordering video tutorial
  42. Vue to achieve seven cattle cloud upload image function
  43. vue.js Environment configuration steps and NPM run dev error reporting solution
  44. 什么是HTTPS以及如何实施HTTPS?
  45. vue使用sdk进行七牛上传
  46. JavaScript 邮箱验证 - 正则验证
  47. Codeless development platform cloud watch sets off a "new revolution" in enterprise Digitalization
  48. Codeless development of cloud watch for enterprise digital solution
  49. What is HTTPS and how to implement it?
  50. Vue uses SDK to upload seven cows
  51. JavaScript mailbox verification - regular verification
  52. JavaScriptBOM操作
  53. JavaScript BOM operation
  54. How to create a new NPM package and publish it to the NPM community
  55. vue --tinymce 解决上传图片的方法
  56. Vue development
  57. A simple solution for vite to batch introduce SVG symbol
  58. Building 3D rendering engine from scratch with JS (2)
  59. Vue -- tinymece solution to upload pictures
  60. Common configuration of nginx