webpack的核心Compiler实现,Compiler类是webpack的运行入口。每次打包都会生成一个实例,里面有很多打包好的数据。这里简化了结构,力求理解关键的封装过程。1.编译器类初始化分析import语句保存依赖图生成入口代码/***1.定义编译器类*/classCompiler{constructor(options){const{entry,output}=options;this.entry=条目;这个。输出=输出;this.modules=[];}//buildstartrun(){}//重写require函数,输出Bundlegenerate(){}}2.Compiler中importimportparsingwebpack.config.jsconstpath=require('path')module.exports={//条目:path.resolve(__dirname,'./src/index.js'),条目:'./src/index.js',输出:{path:path.resolve(__dirname,'./dist'),filename:'main.js'}}compiler.js/***2.解析入口文件得到AST*/constfs=require('fs');constparser=require('@babel/parser');constoptions=require('../webpack.config');constParser={getAst:path=>{//读取入口文件constcontent=fs.readFileSync(path,'utf-8');//将文件内容转换为AST抽象语法树返回nparser.parse(content,{sourceType:'module'})}}classCompiler{constructor(options){const{entry,output}=选项;this.entry=条目;这个。输出=输出;this.modules=[];}//构建开始run(){constast=Parser.getAst(this.entry);console.log(Object.keys(ast));控制台日志(AST);}//覆盖require函数,输出bundlegenerate(){}}newCompiler(options).run();仓库地址
