📚 实现最简 webpack
读取文件内容一共分为两步
- 使用
fs.readFileSync
读取内容
- 使用
@babel-parser
解析 AST 树, 获取代码(node.source.value
) - 使用
@babel/traverse
遍历 AST 树, 获取代码的依赖, 添加到deps
中 - 使用
babel-core
将 ESM 的代码转换成 CJS 的代码
createAsset
返回
{
filePath, // 文件路径
code, // 生成的代码
deps, // 文件的依赖
mapping: {}, // 用于查找的索引, 初始化为空
id, // 索引的id
}
遍历入口文件的deps
, 为所有的dep
调用createAsset
, 将结果放到一个queue
中, 作为graph
返回
这里会把文件路径filePath
作为mapping
的key
, id
为value
, 给mapping
赋值
循环生成的依赖图graph
, 获取code, id, mapping
, 通过ejs
模板, 调用fs.writeFileSync
写入bundle.js
通过id
, 去寻找mapping
中的依赖, 并执行
最终会打包成一个立即执行函数, 参数为mapping
后的所有依赖
// 一个文件的例子
1: [ // id
function (require, module, exports) {
const { foo } = require('./foo.js')
foo()
console.log('main.js')
},
{ './foo.js': 2 }
],
node index.js
打开example
中的index.html
成功后在控制台会输出
foo
bar
main.js