手写简易webpack
# 流程

# 代码解析
配置文件, 只要入口和出口就够了
module.exports = {
entry: path.join(__dirname, 'src/index.js'),
output: {
path: path.join(__dirname, 'dist'),
filename: 'main.js'
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
compiler.js
class Compiler {
constructor(options) {
const { entry, output } = options
this.entry = entry
this.output = output
this.modules = []
}
run() {
const entryModule = this.buildModule(this.entry, true)
this.modules.push(entryModule)
this.modules.map(_module => {
_module.dependencies.map(dependency => {
this.modules.push(this.buildModule(dependency))
})
})
this.emitFiles()
}
buildModule(filename, isEntry) {
let ast
if (isEntry) {
ast = getAST(filename)
} else {
let absolutePath = path.join(process.cwd(), './src', filename)
ast = getAST(absolutePath)
}
return {
filename,
dependencies: getDependencies(ast),
transformCode: transform(ast)
}
}
emitFiles() {
// ......
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
parse.js模块, 实现三个功能,生成AST语法树、traverse遍历、代码转换。parseSync (opens new window), transformFromAst (opens new window)
const babel = require('@babel/core')
const traverse = require('@babel/traverse').default
const fs = require('fs')
module.exports = {
getAST: (path) => {
const content = fs.readFileSync(path, 'utf-8')
return babel.parseSync(content)
},
getDependencies: (ast) => {
const dependencies = []
traverse(ast, {
ImportDeclaration: ({ node }) => {
dependencies.push(node.source.value)
}
})
return dependencies
},
transform: (ast) => {
const { code, map } = babel.transformFromAst(ast, null, {
'presets': ['@babel/preset-env']
})
console.log('code', code)
console.log('map', map)
return code
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
附Github (opens new window), parse模块需要对AST和Babel有一定了解,看不懂可以先看babel原理
编辑 (opens new window)
上次更新: 2025/07/20, 06:21:22