技术标签: Webpack
[实践系列] 主要是让我们通过实践去加深对一些原理的理解。
[实践系列]你能手写一个 Promise 吗?Yes I promise。
有兴趣的同学可以关注 [实践系列] 。 求 star 求 follow~
本文通过实现一个简单 webpack,来理解它的打包原理,看完不懂直接盘我 !!!
本质上,webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack 处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个 bundle。webpack 就像一条生产线,要经过一系列处理流程后才能将源文件转换成输出结果。 这条生产线上的每个处理流程的职责都是单一的,多个流程之间有存在依赖关系,只有完成当前处理后才能交给下一个流程去处理。 插件就像是一个插入到生产线中的一个功能,在特定的时机对生产线上的资源做处理。
webpack 通过 Tapable 来组织这条复杂的生产线。 webpack 在运行过程中会广播事件,插件只需要监听它所关心的事件,就能加入到这条生产线中,去改变生产线的运作。 webpack 的事件流机制保证了插件的有序性,使得整个系统扩展性很好。 -- 深入浅出 webpack 吴浩麟
入口起点(entry point)指示 webpack 应该使用哪个模块,来作为构建其内部依赖图的开始。
进入入口起点后,webpack 会找出有哪些模块和库是入口起点(直接和间接)依赖的。
每个依赖项随即被处理,最后输出到称之为 bundles 的文件中。
output 属性告诉 webpack 在哪里输出它所创建的 bundles,以及如何命名这些文件,默认值为 ./dist。
基本上,整个应用程序结构,都会被编译到你指定的输出路径的文件夹中。
模块,在 Webpack 里一切皆模块,一个模块对应着一个文件。Webpack 会从配置的 Entry 开始递归找出所有依赖的模块。
代码块,一个 Chunk 由多个模块组合而成,用于代码合并与分割。
loader 让 webpack 能够去处理那些非 JavaScript 文件(webpack 自身只理解 JavaScript)。
loader 可以将所有类型的文件转换为 webpack 能够处理的有效模块,然后你就可以利用 webpack 的打包能力,对它们进行处理。
本质上,webpack loader 将所有类型的文件,转换为应用程序的依赖图(和最终的 bundle)可以直接引用的模块。
loader 被用于转换某些类型的模块,而插件则可以用于执行范围更广的任务。
插件的范围包括,从打包优化和压缩,一直到重新定义环境中的变量。插件接口功能极其强大,可以用来处理各种各样的任务。
Webpack 的运行流程是一个串行的过程,从启动到结束会依次执行以下流程 :
在以上过程中,Webpack 会在特定的时间点广播出特定的事件,插件在监听到感兴趣的事件后会执行特定的逻辑,并且插件可以调用 Webpack 提供的 API 改变 Webpack 的运行结果。
class Compiler {
constructor(options) {
// webpack 配置
const { entry, output } = options
// 入口
this.entry = entry
// 出口
this.output = output
// 模块
this.modules = []
}
// 构建启动
run() {}
// 重写 require函数,输出bundle
generate() {}
}
我们这里使用@babel/parser,这是 babel7 的工具,来帮助我们分析内部的语法,包括 es6,返回一个 AST 抽象语法树。
// webpack.config.js
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'main.js'
}
}
//
const fs = require('fs')
const parser = require('@babel/parser')
const options = require('./webpack.config')
const Parser = {
getAst: path => {
// 读取入口文件
const content = fs.readFileSync(path, 'utf-8')
// 将文件内容转为AST抽象语法树
return parser.parse(content, {
sourceType: 'module'
})
}
}
class Compiler {
constructor(options) {
// webpack 配置
const { entry, output } = options
// 入口
this.entry = entry
// 出口
this.output = output
// 模块
this.modules = []
}
// 构建启动
run() {
const ast = Parser.getAst(this.entry)
}
// 重写 require函数,输出bundle
generate() {}
}
new Compiler(options).run()
Babel 提供了@babel/traverse(遍历)方法维护这 AST 树的整体状态,我们这里使用它来帮我们找出依赖模块。
const fs = require('fs')
const path = require('path')
const options = require('./webpack.config')
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const Parser = {
getAst: path => {
// 读取入口文件
const content = fs.readFileSync(path, 'utf-8')
// 将文件内容转为AST抽象语法树
return parser.parse(content, {
sourceType: 'module'
})
},
getDependecies: (ast, filename) => {
const dependecies = {}
// 遍历所有的 import 模块,存入dependecies
traverse(ast, {
// 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
ImportDeclaration({ node }) {
const dirname = path.dirname(filename)
// 保存依赖模块路径,之后生成依赖关系图需要用到
const filepath = './' + path.join(dirname, node.source.value)
dependecies[node.source.value] = filepath
}
})
return dependecies
}
}
class Compiler {
constructor(options) {
// webpack 配置
const { entry, output } = options
// 入口
this.entry = entry
// 出口
this.output = output
// 模块
this.modules = []
}
// 构建启动
run() {
const { getAst, getDependecies } = Parser
const ast = getAst(this.entry)
const dependecies = getDependecies(ast, this.entry)
}
// 重写 require函数,输出bundle
generate() {}
}
new Compiler(options).run()
将 AST 语法树转换为浏览器可执行代码,我们这里使用@babel/core 和 @babel/preset-env。
const fs = require('fs')
const path = require('path')
const options = require('./webpack.config')
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const { transformFromAst } = require('@babel/core')
const Parser = {
getAst: path => {
// 读取入口文件
const content = fs.readFileSync(path, 'utf-8')
// 将文件内容转为AST抽象语法树
return parser.parse(content, {
sourceType: 'module'
})
},
getDependecies: (ast, filename) => {
const dependecies = {}
// 遍历所有的 import 模块,存入dependecies
traverse(ast, {
// 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
ImportDeclaration({ node }) {
const dirname = path.dirname(filename)
// 保存依赖模块路径,之后生成依赖关系图需要用到
const filepath = './' + path.join(dirname, node.source.value)
dependecies[node.source.value] = filepath
}
})
return dependecies
},
getCode: ast => {
// AST转换为code
const { code } = transformFromAst(ast, null, {
presets: ['@babel/preset-env']
})
return code
}
}
class Compiler {
constructor(options) {
// webpack 配置
const { entry, output } = options
// 入口
this.entry = entry
// 出口
this.output = output
// 模块
this.modules = []
}
// 构建启动
run() {
const { getAst, getDependecies, getCode } = Parser
const ast = getAst(this.entry)
const dependecies = getDependecies(ast, this.entry)
const code = getCode(ast)
}
// 重写 require函数,输出bundle
generate() {}
}
new Compiler(options).run()
const fs = require('fs')
const path = require('path')
const options = require('./webpack.config')
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const { transformFromAst } = require('@babel/core')
const Parser = {
getAst: path => {
// 读取入口文件
const content = fs.readFileSync(path, 'utf-8')
// 将文件内容转为AST抽象语法树
return parser.parse(content, {
sourceType: 'module'
})
},
getDependecies: (ast, filename) => {
const dependecies = {}
// 遍历所有的 import 模块,存入dependecies
traverse(ast, {
// 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
ImportDeclaration({ node }) {
const dirname = path.dirname(filename)
// 保存依赖模块路径,之后生成依赖关系图需要用到
const filepath = './' + path.join(dirname, node.source.value)
dependecies[node.source.value] = filepath
}
})
return dependecies
},
getCode: ast => {
// AST转换为code
const { code } = transformFromAst(ast, null, {
presets: ['@babel/preset-env']
})
return code
}
}
class Compiler {
constructor(options) {
// webpack 配置
const { entry, output } = options
// 入口
this.entry = entry
// 出口
this.output = output
// 模块
this.modules = []
}
// 构建启动
run() {
// 解析入口文件
const info = this.build(this.entry)
this.modules.push(info)
this.modules.forEach(({ dependecies }) => {
// 判断有依赖对象,递归解析所有依赖项
if (dependecies) {
for (const dependency in dependecies) {
this.modules.push(this.build(dependecies[dependency]))
}
}
})
// 生成依赖关系图
const dependencyGraph = this.modules.reduce(
(graph, item) => ({
...graph,
// 使用文件路径作为每个模块的唯一标识符,保存对应模块的依赖对象和文件内容
[item.filename]: {
dependecies: item.dependecies,
code: item.code
}
}),
{}
)
}
build(filename) {
const { getAst, getDependecies, getCode } = Parser
const ast = getAst(filename)
const dependecies = getDependecies(ast, filename)
const code = getCode(ast)
return {
// 文件路径,可以作为每个模块的唯一标识符
filename,
// 依赖对象,保存着依赖模块路径
dependecies,
// 文件内容
code
}
}
// 重写 require函数,输出bundle
generate() {}
}
new Compiler(options).run()
const fs = require('fs')
const path = require('path')
const options = require('./webpack.config')
const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const { transformFromAst } = require('@babel/core')
const Parser = {
getAst: path => {
// 读取入口文件
const content = fs.readFileSync(path, 'utf-8')
// 将文件内容转为AST抽象语法树
return parser.parse(content, {
sourceType: 'module'
})
},
getDependecies: (ast, filename) => {
const dependecies = {}
// 遍历所有的 import 模块,存入dependecies
traverse(ast, {
// 类型为 ImportDeclaration 的 AST 节点 (即为import 语句)
ImportDeclaration({ node }) {
const dirname = path.dirname(filename)
// 保存依赖模块路径,之后生成依赖关系图需要用到
const filepath = './' + path.join(dirname, node.source.value)
dependecies[node.source.value] = filepath
}
})
return dependecies
},
getCode: ast => {
// AST转换为code
const { code } = transformFromAst(ast, null, {
presets: ['@babel/preset-env']
})
return code
}
}
class Compiler {
constructor(options) {
// webpack 配置
const { entry, output } = options
// 入口
this.entry = entry
// 出口
this.output = output
// 模块
this.modules = []
}
// 构建启动
run() {
// 解析入口文件
const info = this.build(this.entry)
this.modules.push(info)
this.modules.forEach(({ dependecies }) => {
// 判断有依赖对象,递归解析所有依赖项
if (dependecies) {
for (const dependency in dependecies) {
this.modules.push(this.build(dependecies[dependency]))
}
}
})
// 生成依赖关系图
const dependencyGraph = this.modules.reduce(
(graph, item) => ({
...graph,
// 使用文件路径作为每个模块的唯一标识符,保存对应模块的依赖对象和文件内容
[item.filename]: {
dependecies: item.dependecies,
code: item.code
}
}),
{}
)
this.generate(dependencyGraph)
}
build(filename) {
const { getAst, getDependecies, getCode } = Parser
const ast = getAst(filename)
const dependecies = getDependecies(ast, filename)
const code = getCode(ast)
return {
// 文件路径,可以作为每个模块的唯一标识符
filename,
// 依赖对象,保存着依赖模块路径
dependecies,
// 文件内容
code
}
}
// 重写 require函数 (浏览器不能识别commonjs语法),输出bundle
generate(code) {
// 输出文件路径
const filePath = path.join(this.output.path, this.output.filename)
// 懵逼了吗? 没事,下一节我们捋一捋
const bundle = `(function(graph){
function require(module){
function localRequire(relativePath){
return require(graph[module].dependecies[relativePath])
}
var exports = {};
(function(require,exports,code){
eval(code)
})(localRequire,exports,graph[module].code);
return exports;
}
require('${this.entry}')
})(${JSON.stringify(code)})`
// 把文件内容写入到文件系统
fs.writeFileSync(filePath, bundle, 'utf-8')
}
}
new Compiler(options).run()
我们通过下面的例子来进行讲解,先死亡凝视 30 秒
;(function(graph) {
function require(moduleId) {
function localRequire(relativePath) {
return require(graph[moduleId].dependecies[relativePath])
}
var exports = {}
;(function(require, exports, code) {
eval(code)
})(localRequire, exports, graph[moduleId].code)
return exports
}
require('./src/index.js')
})({
'./src/index.js': {
dependecies: { './hello.js': './src/hello.js' },
code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
},
'./src/hello.js': {
dependecies: {},
code:
'"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
}
})
step 1 : 从入口文件开始执行
// 定义一个立即执行函数,传入生成的依赖关系图
;(function(graph) {
// 重写require函数
function require(moduleId) {
console.log(moduleId) // ./src/index.js
}
// 从入口文件开始执行
require('./src/index.js')
})({
'./src/index.js': {
dependecies: { './hello.js': './src/hello.js' },
code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
},
'./src/hello.js': {
dependecies: {},
code:
'"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
}
})
step 2 : 使用 eval 执行代码
// 定义一个立即执行函数,传入生成的依赖关系图
;(function(graph) {
// 重写require函数
function require(moduleId) {
;(function(code) {
console.log(code) // "use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));
eval(code) // Uncaught TypeError: Cannot read property 'code' of undefined
})(graph[moduleId].code)
}
// 从入口文件开始执行
require('./src/index.js')
})({
'./src/index.js': {
dependecies: { './hello.js': './src/hello.js' },
code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
},
'./src/hello.js': {
dependecies: {},
code:
'"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
}
})
可以看到,我们在执行"./src/index.js"文件代码的时候报错了,这是因为 index.js 里引用依赖 hello.js,而我们没有对依赖进行处理,接下来我们对依赖引用进行处理。
step 3 : 依赖对象寻址映射,获取 exports 对象
// 定义一个立即执行函数,传入生成的依赖关系图
;(function(graph) {
// 重写require函数
function require(moduleId) {
// 找到对应moduleId的依赖对象,调用require函数,eval执行,拿到exports对象
function localRequire(relativePath) {
return require(graph[moduleId].dependecies[relativePath]) // {__esModule: true, say: ƒ say(name)}
}
// 定义exports对象
var exports = {}
;(function(require, exports, code) {
// commonjs语法使用module.exports暴露实现,我们传入的exports对象会捕获依赖对象(hello.js)暴露的实现(exports.say = say)并写入
eval(code)
})(localRequire, exports, graph[moduleId].code)
// 暴露exports对象,即暴露依赖对象对应的实现
return exports
}
// 从入口文件开始执行
require('./src/index.js')
})({
'./src/index.js': {
dependecies: { './hello.js': './src/hello.js' },
code: '"use strict";\n\nvar _hello = require("./hello.js");\n\ndocument.write((0, _hello.say)("webpack"));'
},
'./src/hello.js': {
dependecies: {},
code:
'"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.say = say;\n\nfunction say(name) {\n return "hello ".concat(name);\n}'
}
})
这下应该明白了吧 ~ 可以直接复制上面代码到控制台输出哦~
Webpack 是一个庞大的 Node.js 应用,如果你阅读过它的源码,你会发现实现一个完整的 Webpack 需要编写非常多的代码。 但你无需了解所有的细节,只需了解其整体架构和部分细节即可。对 Webpack 的使用者来说,它是一个简单强大的工具; 对 Webpack 的开发者来说,它是一个扩展性的高系统。
Webpack 之所以能成功,在于它把复杂的实现隐藏了起来,给用户暴露出的只是一个简单的工具,让用户能快速达成目的。 同时整体架构设计合理,扩展性高,开发扩展难度不高,通过社区补足了大量缺失的功能,让 Webpack 几乎能胜任任何场景。
qt xml示范,三种方法
文章浏览阅读953次。今天打开虚拟环境的时候突然报了下面的错误:这是怎末回事,在网上参考了一下,原因是环境变量的问题之类的,然后就直接按照别人的方法操作了一下就可以了代码:unset PYTHONHOMEunset PYTHONPATH成功参考:Fatal Python error: initfsencoding: Unable to get the locale encoding_lei_qi的博客-程序员宅基地..._fatal python error: init_fs_encoding: failed to get the python codec of
搭建eureka的小demo,学习案例
文章浏览阅读2.6k次。因数的和比数字本身大的数称为丰沛数。因数的和比数字本身小的数称为不足数。完全数是一个整数:其因数之和(不含本身打因素)加起来就是数字本身。 1 theNum = int(raw_input('Please input a number to check:')) 2 3 divisor = 1 4 sumOfDivisor = 0 5 6 while divi..._python完全数,丰沛数不足数
文章浏览阅读2.9k次。一、引言之后的项目可能要用到蓝牙,所以打算先吧蓝牙相关的框架都了解整理一下二、整体框架整体框架可以抽象成以下1、驱动层通常蓝牙芯片是通过某个类型的接口与协议栈通讯,接口包括(UART、USB等)2、bluez层bluez为Bluetooth协议栈,往下对接内核代码,往上为用户态程序及工具集而内核代码分为:BlueZ核心协议和驱动程序2.1 BlueZ核心协议位于kernel/net/bluetooth中其中包含hci,l2cap,hid,rfcomm,sco,SDP,BNEP等_bluez和bluedroid
文章浏览阅读633次。Option Explicit'('aliceblue', 'F0F8FF', '艾利斯兰')'('antiquewhite', 'FAEBD7', '古董白')'('aqua', '00FFFF', '浅绿色')'('aquamarine', '7FFFD4', '碧绿色')'('azure', 'F0FFFF', '天蓝色')'('beige', 'F5F5DC', '米色')'('bisque', 'FFE4C4', '桔黄色')'('black', '000000', '黑色..._vb 底 色 浅
文章浏览阅读990次,点赞2次,收藏4次。1,下载ADT链接:https://pan.baidu.com/s/1vmigdQldL0WfTRwZVXG8zw 密码:aak32,安装3,下载SDK tools链接:https://pan.baidu.com/s/1X-hRiyLtMMvuSgzV4tSpZQ 密码:dd4f4,安装sdk5,可以了..._eclipse v4.8 android插件
文章浏览阅读571次。在Java中,枚举(Enumeration)是一种特殊的数据类型,它允许我们定义一个固定数量的常量集合。枚举类型在Java中是通过关键字enum来定义的。每个枚举常量都是枚举类型的实例,它们在枚举类型中以逗号分隔。_java枚举类
文章浏览阅读445次。上一篇:【TeeChart .NET教程】(十八):TeeChart工具集合(上)——其它工具 【下载TeeChart.Net最新版本】 (一)介绍 本教程重点介绍TeeChart for.NetTools,这是一个易于实现的代码单元,用户可以使用这些代码为TeeCharts添加额外的..._teechartnet
文章浏览阅读1.9w次,点赞12次,收藏86次。C++,动态链接库的动态调用,以及如何动态调用库中的函数和类。_调用动态链接库
文章浏览阅读335次。练习一1、定义主函数main() 实现输入名字,通过format格式化字符串2、运行main()# -*- coding: UTF-8 -*-def main(): name = input('请输入名字:') other_name = input('请再输入名字:') print('{}去买车,需要10万元,可{}只带了现金99998元,就差..._文字小游戏
文章浏览阅读5.8k次,点赞2次,收藏6次。Filter(过滤器) 是 Java Servlet 规范中定义的一种组件,用于在请求到达 Servlet 之前或响应返回给客户端之前对请求和响应进行处理。Filter 可以设置多个,并且按照一定顺序依次执行,这是因为使用了设计模式中的职责链模式。_多个filter执行顺序