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

  1. Parse import statements
  2. Save the dependency graph
  3. 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();

Warehouse Address


窗里窗外
367 声望13 粉丝

« 上一篇
BOM-各种宽高