什么是 webpack ?

本质上,webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack 处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个 bundle。> webpack 就像一条生产线,要经过一系列处理流程后才能将源文件转换成输出结果。 这条生产线上的每个处理流程的职责都是单一的,多个流程之间有存在依赖关系,只有完成当前处理后才能交给下一个流程去处理。 插件就像是一个插入到生产线中的一个功能,在特定的时机对生产线上的资源做处理。

webpack 通过 Tapable 来组织这条复杂的生产线。 webpack 在运行过程中会广播事件,插件只需要监听它所关心的事件,就能加入到这条生产线中,去改变生产线的运作。 webpack 的事件流机制保证了插件的有序性,使得整个系统扩展性很好。 — 深入浅出 webpack 吴浩麟

webpack打包原理 - 图1

webpack 核心概念

Entry

入口起点(entry point)指示 webpack 应该使用哪个模块,来作为构建其内部依赖图的开始。
进入入口起点后,webpack 会找出有哪些模块和库是入口起点(直接和间接)依赖的。
每个依赖项随即被处理,最后输出到称之为 bundles 的文件中。

Output

output 属性告诉 webpack 在哪里输出它所创建的 bundles,以及如何命名这些文件,默认值为 ./dist。
基本上,整个应用程序结构,都会被编译到你指定的输出路径的文件夹中。

Module

模块,在 Webpack 里一切皆模块,一个模块对应着一个文件。Webpack 会从配置的 Entry 开始递归找出所有依赖的模块。

Chunk

代码块,一个 Chunk 由多个模块组合而成,用于代码合并与分割。

Loader

loader 让 webpack 能够去处理那些非 JavaScript 文件(webpack 自身只理解 JavaScript)。
loader 可以将所有类型的文件转换为 webpack 能够处理的有效模块,然后你就可以利用 webpack 的打包能力,对它们进行处理。
本质上,webpack loader 将所有类型的文件,转换为应用程序的依赖图(和最终的 bundle)可以直接引用的模块。

Plugin

loader 被用于转换某些类型的模块,而插件则可以用于执行范围更广的任务。
插件的范围包括,从打包优化和压缩,一直到重新定义环境中的变量。插件接口功能极其强大,可以用来处理各种各样的任务。

webpack 构建流程

Webpack 的运行流程是一个串行的过程,从启动到结束会依次执行以下流程 :

  1. 初始化参数:从配置文件和 Shell 语句中读取与合并参数,得出最终的参数。
  2. 开始编译:用上一步得到的参数初始化 Compiler 对象,加载所有配置的插件,执行对象的 run 方法开始执行编译。
  3. 确定入口:根据配置中的 entry 找出所有的入口文件。
  4. 编译模块:从入口文件出发,调用所有配置的 Loader 对模块进行翻译,再找出该模块依赖的模块,再递归本步骤直到所有入口依赖的文件都经过了本步骤的处理。
  5. 完成模块编译:在经过第 4 步使用 Loader 翻译完所有模块后,得到了每个模块被翻译后的最终内容以及它们之间的依赖关系。
  6. 输出资源:根据入口和模块之间的依赖关系,组装成一个个包含多个模块的 Chunk,再把每个 Chunk 转换成一个单独的文件加入到输出列表,这步是可以修改输出内容的最后机会。
  7. 输出完成:在确定好输出内容后,根据配置确定输出的路径和文件名,把文件内容写入到文件系统。

在以上过程中,Webpack 会在特定的时间点广播出特定的事件,插件在监听到感兴趣的事件后会执行特定的逻辑,并且插件可以调用 Webpack 提供的 API 改变 Webpack 的运行结果。

实践加深理解,撸一个简易 webpack

1. 定义 Compiler 类

  1. class Compiler {
  2. constructor(options) {
  3. // webpack 配置
  4. const { entry, output } = options
  5. // 入口
  6. this.entry = entry
  7. // 出口
  8. this.output = output
  9. // 模块
  10. this.modules = []
  11. }
  12. // 构建启动
  13. run() {}
  14. // 重写 require函数,输出bundle
  15. generate() {}
  16. }

2. 解析入口文件,获取 AST

我们这里使用@babel/parser,这是 babel7 的工具,来帮助我们分析内部的语法,包括 es6,返回一个 AST 抽象语法树。

  1. // webpack.config.js
  2. const path = require('path')
  3. module.exports = {
  4. entry: './src/index.js',
  5. output: {
  6. path: path.resolve(__dirname, './dist'),
  7. filename: 'main.js'
  8. }
  9. }
  10. //
  1. const fs = require('fs')
  2. const parser = require('@babel/parser')
  3. const options = require('./webpack.config')
  4. const Parser = {
  5. getAst: path => {
  6. // 读取入口文件
  7. const content = fs.readFileSync(path, 'utf-8')
  8. // 将文件内容转为AST抽象语法树
  9. return parser.parse(content, {
  10. sourceType: 'module'
  11. })
  12. }
  13. }
  14. class Compiler {
  15. constructor(options) {
  16. // webpack 配置
  17. const { entry, output } = options
  18. // 入口
  19. this.entry = entry
  20. // 出口
  21. this.output = output
  22. // 模块
  23. this.modules = []
  24. }
  25. // 构建启动
  26. run() {
  27. const ast = Parser.getAst(this.entry)
  28. }
  29. // 重写 require函数,输出bundle
  30. generate() {}
  31. }
  32. new Compiler(options).run()

3. 找出所有依赖模块

Babel 提供了@babel/traverse(遍历)方法维护这 AST 树的整体状态,我们这里使用它来帮我们找出依赖模块。

  1. const fs = require('fs')
  2. const path = require('path')
  3. const options = require('./webpack.config')
  4. const parser = require('@babel/parser')
  5. const traverse = require('@babel/traverse').default
  6. const Parser = {
  7. getAst: path => {
  8. // 读取入口文件
  9. const content = fs.readFileSync(path, 'utf-8')
  10. // 将文件内容转为AST抽象语法树
  11. return parser.parse(content, {
  12. sourceType: 'module'
  13. })
  14. },
  15. getDependecies: (ast, filename) => {
  16. const dependecies = {}
  17. // 遍历所有的 import 模块,存入dependecies
  18. traverse(ast, {
  19. // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
  20. ImportDeclaration({ node }) {
  21. const dirname = path.dirname(filename)
  22. // 保存依赖模块路径,之后生成依赖关系图需要用到
  23. const filepath = './' + path.join(dirname, node.source.value)
  24. dependecies[node.source.value] = filepath
  25. }
  26. })
  27. return dependecies
  28. }
  29. }
  30. class Compiler {
  31. constructor(options) {
  32. // webpack 配置
  33. const { entry, output } = options
  34. // 入口
  35. this.entry = entry
  36. // 出口
  37. this.output = output
  38. // 模块
  39. this.modules = []
  40. }
  41. // 构建启动
  42. run() {
  43. const { getAst, getDependecies } = Parser
  44. const ast = getAst(this.entry)
  45. const dependecies = getDependecies(ast, this.entry)
  46. }
  47. // 重写 require函数,输出bundle
  48. generate() {}
  49. }
  50. new Compiler(options).run()

4. AST 转换为 code

将 AST 语法树转换为浏览器可执行代码,我们这里使用@babel/core 和 @babel/preset-env。

  1. const fs = require('fs')
  2. const path = require('path')
  3. const options = require('./webpack.config')
  4. const parser = require('@babel/parser')
  5. const traverse = require('@babel/traverse').default
  6. const { transformFromAst } = require('@babel/core')
  7. const Parser = {
  8. getAst: path => {
  9. // 读取入口文件
  10. const content = fs.readFileSync(path, 'utf-8')
  11. // 将文件内容转为AST抽象语法树
  12. return parser.parse(content, {
  13. sourceType: 'module'
  14. })
  15. },
  16. getDependecies: (ast, filename) => {
  17. const dependecies = {}
  18. // 遍历所有的 import 模块,存入dependecies
  19. traverse(ast, {
  20. // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
  21. ImportDeclaration({ node }) {
  22. const dirname = path.dirname(filename)
  23. // 保存依赖模块路径,之后生成依赖关系图需要用到
  24. const filepath = './' + path.join(dirname, node.source.value)
  25. dependecies[node.source.value] = filepath
  26. }
  27. })
  28. return dependecies
  29. },
  30. getCode: ast => {
  31. // AST转换为code
  32. const { code } = transformFromAst(ast, null, {
  33. presets: ['@babel/preset-env']
  34. })
  35. return code
  36. }
  37. }
  38. class Compiler {
  39. constructor(options) {
  40. // webpack 配置
  41. const { entry, output } = options
  42. // 入口
  43. this.entry = entry
  44. // 出口
  45. this.output = output
  46. // 模块
  47. this.modules = []
  48. }
  49. // 构建启动
  50. run() {
  51. const { getAst, getDependecies, getCode } = Parser
  52. const ast = getAst(this.entry)
  53. const dependecies = getDependecies(ast, this.entry)
  54. const code = getCode(ast)
  55. }
  56. // 重写 require函数,输出bundle
  57. generate() {}
  58. }
  59. new Compiler(options).run()

5. 递归解析所有依赖项,生成依赖关系图

  1. const fs = require('fs')
  2. const path = require('path')
  3. const options = require('./webpack.config')
  4. const parser = require('@babel/parser')
  5. const traverse = require('@babel/traverse').default
  6. const { transformFromAst } = require('@babel/core')
  7. const Parser = {
  8. getAst: path => {
  9. // 读取入口文件
  10. const content = fs.readFileSync(path, 'utf-8')
  11. // 将文件内容转为AST抽象语法树
  12. return parser.parse(content, {
  13. sourceType: 'module'
  14. })
  15. },
  16. getDependecies: (ast, filename) => {
  17. const dependecies = {}
  18. // 遍历所有的 import 模块,存入dependecies
  19. traverse(ast, {
  20. // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
  21. ImportDeclaration({ node }) {
  22. const dirname = path.dirname(filename)
  23. // 保存依赖模块路径,之后生成依赖关系图需要用到
  24. const filepath = './' + path.join(dirname, node.source.value)
  25. dependecies[node.source.value] = filepath
  26. }
  27. })
  28. return dependecies
  29. },
  30. getCode: ast => {
  31. // AST转换为code
  32. const { code } = transformFromAst(ast, null, {
  33. presets: ['@babel/preset-env']
  34. })
  35. return code
  36. }
  37. }
  38. class Compiler {
  39. constructor(options) {
  40. // webpack 配置
  41. const { entry, output } = options
  42. // 入口
  43. this.entry = entry
  44. // 出口
  45. this.output = output
  46. // 模块
  47. this.modules = []
  48. }
  49. // 构建启动
  50. run() {
  51. // 解析入口文件
  52. const info = this.build(this.entry)
  53. this.modules.push(info)
  54. this.modules.forEach(({ dependecies }) => {
  55. // 判断有依赖对象,递归解析所有依赖项
  56. if (dependecies) {
  57. for (const dependency in dependecies) {
  58. this.modules.push(this.build(dependecies[dependency]))
  59. }
  60. }
  61. })
  62. // 生成依赖关系图
  63. const dependencyGraph = this.modules.reduce(
  64. (graph, item) => ({
  65. ...graph,
  66. // 使用文件路径作为每个模块的唯一标识符,保存对应模块的依赖对象和文件内容
  67. [item.filename]: {
  68. dependecies: item.dependecies,
  69. code: item.code
  70. }
  71. }),
  72. {}
  73. )
  74. }
  75. build(filename) {
  76. const { getAst, getDependecies, getCode } = Parser
  77. const ast = getAst(filename)
  78. const dependecies = getDependecies(ast, filename)
  79. const code = getCode(ast)
  80. return {
  81. // 文件路径,可以作为每个模块的唯一标识符
  82. filename,
  83. // 依赖对象,保存着依赖模块路径
  84. dependecies,
  85. // 文件内容
  86. code
  87. }
  88. }
  89. // 重写 require函数,输出bundle
  90. generate() {}
  91. }
  92. new Compiler(options).run()

6. 重写 require 函数,输出 bundle

  1. const fs = require('fs')
  2. const path = require('path')
  3. const options = require('./webpack.config')
  4. const parser = require('@babel/parser')
  5. const traverse = require('@babel/traverse').default
  6. const { transformFromAst } = require('@babel/core')
  7. const Parser = {
  8. getAst: path => {
  9. // 读取入口文件
  10. const content = fs.readFileSync(path, 'utf-8')
  11. // 将文件内容转为AST抽象语法树
  12. return parser.parse(content, {
  13. sourceType: 'module'
  14. })
  15. },
  16. getDependecies: (ast, filename) => {
  17. const dependecies = {}
  18. // 遍历所有的 import 模块,存入dependecies
  19. traverse(ast, {
  20. // 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
  21. ImportDeclaration({ node }) {
  22. const dirname = path.dirname(filename)
  23. // 保存依赖模块路径,之后生成依赖关系图需要用到
  24. const filepath = './' + path.join(dirname, node.source.value)
  25. dependecies[node.source.value] = filepath
  26. }
  27. })
  28. return dependecies
  29. },
  30. getCode: ast => {
  31. // AST转换为code
  32. const { code } = transformFromAst(ast, null, {
  33. presets: ['@babel/preset-env']
  34. })
  35. return code
  36. }
  37. }
  38. class Compiler {
  39. constructor(options) {
  40. // webpack 配置
  41. const { entry, output } = options
  42. // 入口
  43. this.entry = entry
  44. // 出口
  45. this.output = output
  46. // 模块
  47. this.modules = []
  48. }
  49. // 构建启动
  50. run() {
  51. // 解析入口文件
  52. const info = this.build(this.entry)
  53. this.modules.push(info)
  54. this.modules.forEach(({ dependecies }) => {
  55. // 判断有依赖对象,递归解析所有依赖项
  56. if (dependecies) {
  57. for (const dependency in dependecies) {
  58. this.modules.push(this.build(dependecies[dependency]))
  59. }
  60. }
  61. })
  62. // 生成依赖关系图
  63. const dependencyGraph = this.modules.reduce(
  64. (graph, item) => ({
  65. ...graph,
  66. // 使用文件路径作为每个模块的唯一标识符,保存对应模块的依赖对象和文件内容
  67. [item.filename]: {
  68. dependecies: item.dependecies,
  69. code: item.code
  70. }
  71. }),
  72. {}
  73. )
  74. this.generate(dependencyGraph)
  75. }
  76. build(filename) {
  77. const { getAst, getDependecies, getCode } = Parser
  78. const ast = getAst(filename)
  79. const dependecies = getDependecies(ast, filename)
  80. const code = getCode(ast)
  81. return {
  82. // 文件路径,可以作为每个模块的唯一标识符
  83. filename,
  84. // 依赖对象,保存着依赖模块路径
  85. dependecies,
  86. // 文件内容
  87. code
  88. }
  89. }
  90. // 重写 require函数 (浏览器不能识别commonjs语法),输出bundle
  91. generate(code) {
  92. // 输出文件路径
  93. const filePath = path.join(this.output.path, this.output.filename)
  94. // 懵逼了吗? 没事,下一节我们捋一捋
  95. const bundle = `(function(graph){
  96. function require(module){
  97. function localRequire(relativePath){
  98. return require(graph[module].dependecies[relativePath])
  99. }
  100. var exports = {};
  101. (function(require,exports,code){
  102. eval(code)
  103. })(localRequire,exports,graph[module].code);
  104. return exports;
  105. }
  106. require('${this.entry}')
  107. })(${JSON.stringify(code)})`
  108. // 把文件内容写入到文件系统
  109. fs.writeFileSync(filePath, bundle, 'utf-8')
  110. }
  111. }
  112. new Compiler(options).run()

7. 看完这节,彻底搞懂 bundle 实现

我们通过下面的例子来进行讲解,先死亡凝视 30 秒

  1. ;(function(graph) {
  2. function require(moduleId) {
  3. function localRequire(relativePath) {
  4. return require(graph[moduleId].dependecies[relativePath])
  5. }
  6. var exports = {}
  7. ;(function(require, exports, code) {
  8. eval(code)
  9. })(localRequire, exports, graph[moduleId].code)
  10. return exports
  11. }
  12. require('./src/index.js')
  13. })({
  14. './src/index.js': {
  15. dependecies: { './hello.js': './src/hello.js' },
  16. code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
  17. },
  18. './src/hello.js': {
  19. dependecies: {},
  20. code:
  21. '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
  22. }
  23. })

step 1 : 从入口文件开始执行

  1. // 定义一个立即执行函数,传入生成的依赖关系图
  2. ;(function(graph) {
  3. // 重写require函数
  4. function require(moduleId) {
  5. console.log(moduleId) // ./src/index.js
  6. }
  7. // 从入口文件开始执行
  8. require('./src/index.js')
  9. })({
  10. './src/index.js': {
  11. dependecies: { './hello.js': './src/hello.js' },
  12. code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
  13. },
  14. './src/hello.js': {
  15. dependecies: {},
  16. code:
  17. '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
  18. }
  19. })

step 2 : 使用 eval 执行代码

  1. // 定义一个立即执行函数,传入生成的依赖关系图
  2. ;(function(graph) {
  3. // 重写require函数
  4. function require(moduleId) {
  5. ;(function(code) {
  6. console.log(code) // "use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));
  7. eval(code) // Uncaught TypeError: Cannot read property 'code' of undefined
  8. })(graph[moduleId].code)
  9. }
  10. // 从入口文件开始执行
  11. require('./src/index.js')
  12. })({
  13. './src/index.js': {
  14. dependecies: { './hello.js': './src/hello.js' },
  15. code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
  16. },
  17. './src/hello.js': {
  18. dependecies: {},
  19. code:
  20. '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
  21. }
  22. })

可以看到,我们在执行”./src/index.js”文件代码的时候报错了,这是因为 index.js 里引用依赖 hello.js,而我们没有对依赖进行处理,接下来我们对依赖引用进行处理。

step 3 : 依赖对象寻址映射,获取 exports 对象

  1. // 定义一个立即执行函数,传入生成的依赖关系图
  2. ;(function(graph) {
  3. // 重写require函数
  4. function require(moduleId) {
  5. // 找到对应moduleId的依赖对象,调用require函数,eval执行,拿到exports对象
  6. function localRequire(relativePath) {
  7. return require(graph[moduleId].dependecies[relativePath]) // {__esModule: true, say: ƒ say(name)}
  8. }
  9. // 定义exports对象
  10. var exports = {}
  11. ;(function(require, exports, code) {
  12. // commonjs语法使用module.exports暴露实现,我们传入的exports对象会捕获依赖对象(hello.js)暴露的实现(exports.say = say)并写入
  13. eval(code)
  14. })(localRequire, exports, graph[moduleId].code)
  15. // 暴露exports对象,即暴露依赖对象对应的实现
  16. return exports
  17. }
  18. // 从入口文件开始执行
  19. require('./src/index.js')
  20. })({
  21. './src/index.js': {
  22. dependecies: { './hello.js': './src/hello.js' },
  23. code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
  24. },
  25. './src/hello.js': {
  26. dependecies: {},
  27. code:
  28. '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
  29. }
  30. })

这下应该明白了吧 ~ 可以直接复制上面代码到控制台输出哦~
完整代码地址戳我 👈

总结

Webpack 是一个庞大的 Node.js 应用,如果你阅读过它的源码,你会发现实现一个完整的 Webpack 需要编写非常多的代码。 但你无需了解所有的细节,只需了解其整体架构和部分细节即可。> 对 Webpack 的使用者来说,它是一个简单强大的工具; 对 Webpack 的开发者来说,它是一个扩展性的高系统。

Webpack 之所以能成功,在于它把复杂的实现隐藏了起来,给用户暴露出的只是一个简单的工具,让用户能快速达成目的。 同时整体架构设计合理,扩展性高,开发扩展难度不高,通过社区补足了大量缺失的功能,让 Webpack 几乎能胜任任何场景。。