webpack DefinePlugin源碼入口解析
正文
DefinePlugin是webpack的一個官方內置插件,它允許在 編譯時 將你代碼中的變量替換為其他值或表達式。這在需要根據開發模式與生產模式進行不同的操作時,非常有用。例如,如果想在開發構建中進行日志記錄,而不在生產構建中進行,就可以定義一個全局常量去判斷是否記錄日志。這就是 DefinePlugin 的發光之處,設置好它,就可以忘掉開發環境和生產環境的構建規則。
new webpack.DefinePlugin({ PRODUCTION: JSON.stringify(true), VERSION: JSON.stringify('5fa3b9'), BROWSER_SUPPORTS_HTML5: true, TWO: '1+1', 'typeof window': JSON.stringify('object'), 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), });
demo
console.log(PRODUCTION,VERSION,BROWSER_SUPPORTS_HTML5,TWO,typeof window,process.env.NODE_ENV);
源碼入口
parser是一個hookMap,它就相當於一個管理hook的Map結構。
apply(compiler) { const definitions = this.definitions; compiler.hooks.compilation.tap( "DefinePlugin", (compilation, { normalModuleFactory }) => { //... normalModuleFactory.hooks.parser .for("javascript/auto") .tap("DefinePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("DefinePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("DefinePlugin", handler); //... }) }
parser的call時機在哪?完全就在於NormalModuleFactory.createParser時機
所以這個鉤子的語義就是parser創建時的初始化鉤子。
createParser(type, parserOptions = {}) { parserOptions = mergeGlobalOptions( this._globalParserOptions, type, parserOptions ); const parser = this.hooks.createParser.for(type).call(parserOptions); if (!parser) { throw new Error(`No parser registered for ${type}`); } this.hooks.parser.for(type).call(parser, parserOptions); return parser; }
好,現在讓我們看看具體初始化瞭什麼邏輯。
首先現在program上定義一個鉤子,在遍歷JavaScript AST前(該時機由program定義位置所知),註冊buildInfo.valueDependencies=new Map();
並定義
buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
const handler = parser => { const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN); //mainValue是在DefinePlugin最初初始化時定義到compilation.valueCacheVersions上的 parser.hooks.program.tap("DefinePlugin", () => { const { buildInfo } = parser.state.module; if (!buildInfo.valueDependencies) buildInfo.valueDependencies = new Map(); buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue); }); //.... walkDefinitions(definitions, ""); }
然後開始遍歷Definitions(這是用戶提供的配置項,比如 PRODUCTION: JSON.stringify(true),)
const walkDefinitions = (definitions, prefix) => { Object.keys(definitions).forEach(key => { const code = definitions[key]; if ( code && typeof code === "object" && !(code instanceof RuntimeValue) && !(code instanceof RegExp) ) { //如果是對象就遞歸調用 walkDefinitions(code, prefix + key + "."); applyObjectDefine(prefix + key, code); return; } applyDefineKey(prefix, key); applyDefine(prefix + key, code); }); };
applyDefine
const applyDefine = (key, code) => { const originalKey = key; const isTypeof = /^typeof\s+/.test(key); if (isTypeof) key = key.replace(/^typeof\s+/, ""); let recurse = false; let recurseTypeof = false; if (!isTypeof) { parser.hooks.canRename.for(key).tap("DefinePlugin", () => { addValueDependency(originalKey); return true; }); parser.hooks.evaluateIdentifier .for(key) .tap("DefinePlugin", expr => { /** * this is needed in case there is a recursion in the DefinePlugin * to prevent an endless recursion * e.g.: new DefinePlugin({ * "a": "b", * "b": "a" * }); */ if (recurse) return; addValueDependency(originalKey); recurse = true; const res = parser.evaluate( toCode( code, parser, compilation.valueCacheVersions, key, runtimeTemplate, null ) ); recurse = false; res.setRange(expr.range); return res; }); parser.hooks.expression.for(key).tap("DefinePlugin", expr => { addValueDependency(originalKey); const strCode = toCode( code, parser, compilation.valueCacheVersions, originalKey, runtimeTemplate, !parser.isAsiPosition(expr.range[0]) ); if (/__webpack_require__\s*(!?.)/.test(strCode)) { return toConstantDependency(parser, strCode, [ RuntimeGlobals.require ])(expr); } else if (/__webpack_require__/.test(strCode)) { return toConstantDependency(parser, strCode, [ RuntimeGlobals.requireScope ])(expr); } else { return toConstantDependency(parser, strCode)(expr); } }); } parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { /** * this is needed in case there is a recursion in the DefinePlugin * to prevent an endless recursion * e.g.: new DefinePlugin({ * "typeof a": "typeof b", * "typeof b": "typeof a" * }); */ if (recurseTypeof) return; recurseTypeof = true; addValueDependency(originalKey); const codeCode = toCode( code, parser, compilation.valueCacheVersions, originalKey, runtimeTemplate, null ); const typeofCode = isTypeof ? codeCode : "typeof (" + codeCode + ")"; const res = parser.evaluate(typeofCode); recurseTypeof = false; res.setRange(expr.range); return res; }); parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { addValueDependency(originalKey); const codeCode = toCode( code, parser, compilation.valueCacheVersions, originalKey, runtimeTemplate, null ); const typeofCode = isTypeof ? codeCode : "typeof (" + codeCode + ")"; const res = parser.evaluate(typeofCode); if (!res.isString()) return; return toConstantDependency( parser, JSON.stringify(res.string) ).bind(parser)(expr); }); };
hooks.expression
在applyDefine中定義的hooks.expression定義瞭對表達式的替換處理。
當代碼解析到語句【key】時,便會觸發如下鉤子邏輯,不過先別急,我們先搞清楚expression鉤子在何處會被觸發。
parser.hooks.expression.for(key).tap("DefinePlugin", expr => { //... }
觸發時機
單單指demo中的情況
比如PRODUCTION會被acron解析為Identifier
而在parse階段中,會有這麼一句
if (this.hooks.program.call(ast, comments) === undefined) { //...其他解析語句 this.walkStatements(ast.body); } //然後會走到這 walkIdentifier(expression) { this.callHooksForName(this.hooks.expression, expression.name, expression); } //最後 const hook = hookMap.get(name);//獲取hook if (hook !== undefined) { const result = hook.call(...args); //執行hook if (result !== undefined) return result; }
具體邏輯
parser.hooks.expression.for(key).tap("DefinePlugin", expr =>{ addValueDependency(originalKey); const strCode = toCode( code, parser, compilation.valueCacheVersions, originalKey, runtimeTemplate, !parser.isAsiPosition(expr.range[0]) ); if (/__webpack_require__\s*(!?.)/.test(strCode)) { return toConstantDependency(parser, strCode, [ RuntimeGlobals.require ])(expr); } else if (/__webpack_require__/.test(strCode)) { return toConstantDependency(parser, strCode, [ RuntimeGlobals.requireScope ])(expr); } else { return toConstantDependency(parser, strCode)(expr); } }); }
addValueDependency
//這裡會影響needBuild的邏輯,是控制是否構建模塊的 const addValueDependency = key => { const { buildInfo } = parser.state.module; //這裡就可以理解為設置key,value buildInfo.valueDependencies.set( VALUE_DEP_PREFIX + key, compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key) ); };
要搞懂addValueDependency到底做瞭什麼,首先得理解
- compilation.valueCacheVersions這個map結構做瞭什麼?
- buildInfo.valueDependencies這裡的依賴收集起來有什麼用?
toCode獲取strCode
toConstantDependency
設置ConstDependency靜態轉換依賴。
exports.toConstantDependency = (parser, value, runtimeRequirements) => { return function constDependency(expr) { const dep = new ConstDependency(value, expr.range, runtimeRequirements); dep.loc = expr.loc; parser.state.module.addPresentationalDependency(dep); return true; }; };
ConstDependency是如何替換源碼的?
出處在seal階段
if (module.presentationalDependencies !== undefined) { for (const dependency of module.presentationalDependencies) { this.sourceDependency( module, dependency, initFragments, source, generateContext ); } }
sourceDenpendency,會獲取依賴上的執行模板
const constructor = /** @type {new (...args: any[]) => Dependency} */ ( dependency.constructor ); //template可以理解為代碼生成模板 const template = generateContext.dependencyTemplates.get(constructor); ///.... template.apply(dependency, source, templateContext);//然後執行
而ConstPendency的執行模板直接替換瞭源碼中的某個片段內容
const dep = /** @type {ConstDependency} */ (dependency); if (dep.runtimeRequirements) { for (const req of dep.runtimeRequirements) { templateContext.runtimeRequirements.add(req); } } if (typeof dep.range === "number") { source.insert(dep.range, dep.expression); return; } source.replace(dep.range[0], dep.range[1] - 1, dep.expression);
hooks.canRename
在applyDefine中,也有hooks.canRename的調用:
parser.hooks.canRename.for(key).tap("DefinePlugin", () => { addValueDependency(key); return true; });
在這裡其實就是允許key可以被重命名,並借機收集key作為依賴,但這個重命名的工作不是替換,並不在definePlugin內做,有點點奇怪。
詳細:
該hook會在js ast遍歷時多處被call
- walkAssignmentExpression 賦值表達式
- _walkIIFE CallExpression 函數調用表達式發現是IIFE時
- walkVariableDeclaration 聲明語句
canRename有什麼用?其實是配合rename使用的鉤子
當其返回true,rename鉤子才能起作用。如下:
walkVariableDeclaration(statement) { for (const declarator of statement.declarations) { switch (declarator.type) { case "VariableDeclarator": { const renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init); if (renameIdentifier && declarator.id.type === "Identifier") { const hook = this.hooks.canRename.get(renameIdentifier); if (hook !== undefined && hook.call(declarator.init)) { // renaming with "var a = b;" const hook = this.hooks.rename.get(renameIdentifier); if (hook === undefined || !hook.call(declarator.init)) { this.setVariable(declarator.id.name, renameIdentifier); } break; } } //... } } } }
官方也有所介紹這個鉤子
hooks.typeof
parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { addValueDependency(originalKey); const codeCode = toCode( code, parser, compilation.valueCacheVersions, originalKey, runtimeTemplate, null ); const typeofCode = isTypeof ? codeCode : "typeof (" + codeCode + ")"; const res = parser.evaluate(typeofCode); if (!res.isString()) return; return toConstantDependency( parser, JSON.stringify(res.string) ).bind(parser)(expr); });
先執行typeof再用toConstantDependency替換。。
以上就是webpack DefinePlugin源碼入口解析的詳細內容,更多關於webpack DefinePlugin入口的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- vue3的hooks用法總結
- 80行代碼寫一個Webpack插件並發佈到npm
- vue3中hooks的簡介及用法教程
- Vue3編程流暢技巧自定義Hooks
- 淺談Webpack4 plugins 實現原理