webpack 核心 Compiler 实现(系列一)

网友投稿 705 2022-10-25 15:55:00

webpack 核心 Compiler 实现(系列一)

webpack 核心 Compiler 实现

Compiler 类是 webpack的运行入口,每次打包时,会生成一个实例,里面挂载了许多打包的数据,在这里简化了结构,力求了解关键性打包流程

1. Compiler类初始化

解析 import 语句保存依赖图生成入口代码

/** * 1. 定义 Compiler 类 */class Compiler { constructor(options) { const { entry, output } = options; this.entry = entry; this.output = output; this.modules = []; } // 构建启动 run(){} // 重写 require 函数,输出 Bundle generate() {}}

2. Compiler 中的import导入解析

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:手把手教你在 Vue3 中自定义指令
下一篇:ZBJCalendar是一个简单的日历iOS的框架
相关文章