Skip to content

cuiyiming1998/webpack-mini

Repository files navigation

mini-webpack

📚 实现最简 webpack

读取文件内容createAsset

读取文件内容一共分为两步

读取内容

  • 使用fs.readFileSync读取内容

获取文件的依赖关系

  • 使用@babel-parser解析 AST 树, 获取代码(node.source.value)
  • 使用@babel/traverse遍历 AST 树, 获取代码的依赖, 添加到deps
  • 使用babel-core将 ESM 的代码转换成 CJS 的代码

createAsset返回

{
  filePath, // 文件路径
  code, // 生成的代码
  deps, // 文件的依赖
  mapping: {}, // 用于查找的索引, 初始化为空
  id, // 索引的id
}

生成依赖图createGraph

遍历入口文件的deps, 为所有的dep调用createAsset, 将结果放到一个queue中, 作为graph返回

这里会把文件路径filePath作为mappingkey, idvalue, 给mapping赋值

生成模板build

循环生成的依赖图graph, 获取code, id, mapping, 通过ejs模板, 调用fs.writeFileSync写入bundle.js

require

通过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

About

📚 实现最简webpack

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published