webpack core Compiler implementation
The Compiler class is the running entry of webpack. Each time it is packaged, an instance will be generated in which a lot of packaged data is mounted. The structure is simplified here, and we strive to understand the key packaging process.
1. Compiler class initialization
- Parse import statements
- Save the dependency graph
- Generate entry code
/**
* 1. 定义 Compiler 类
*/
class Compiler {
constructor(options) {
const { entry, output } = options;
this.entry = entry;
this.output = output;
this.modules = [];
}
// 构建启动
run(){}
// 重写 require 函数,输出 Bundle
generate() {}
}
2. Import import analysis in Compiler
webpack.config.js
const path = require('path')
module.exports = {
// entry: path.resolve(__dirname, './src/index.js'),
entry: './src/index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'main.js'
}
}
compiler.js
/**
* 2. 解析入口文件,获取 AST
*/
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) {
const { entry, output } = options;
this.entry = entry;
this.output = output;
this.modules = [];
}
// 构建启动
run() {
const ast = Parser.getAst(this.entry);
console.log(Object.keys(ast));
console.log(ast);
}
// 重写 require函数,输出 bundle
generate() {
}
}
new Compiler(options).run();
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。