1. 自己寫一個loader
來看markdownd的loader
const marked = require("marked");
//官方提供的一個工具庫
const loaderUtils = require("loader-utils");
module.exports = function (markdown) {
// merge params and default config
//獲得webpack.conifg.js的一些核心配置
//this構(gòu)建上下文的信息
const options = loaderUtils.getOptions(this);
this.cacheable();
//對已有的文件 正則匹配 要不就用AST
marked.setOptions(options);
return marked(markdown);
};
2. ast語法樹解析
const code = "const a = 1";
let acorn = require("acorn");
const walk = require("acorn-walk");
const result = acorn.parse(code);
console.log(result);
walk.simple(result,{
Literal(node) {
console.log(`Found a literal: ${node.value}`)
}
});
ast解析,修改,整合
const esprima = require('esprima');
const estraverse = require("estraverse");
const escodegen = require("escodegen");
const code = `const view = {
a:3,
init:()=>{
view.a = 4;
},
render: ()=> {
}
}`;
const ast = esprima.parse(code);
// console.log(ast);
estraverse.traverse(ast, {
enter: function (node, parent) {
if(node.type =="VariableDeclaration"){
console.log("??",node.kind)
node.kind = "var";
}
}
});
const generated_code = escodegen.generate(ast);
console.log(JSON.stringify(generated_code,null,4));
3. plugin編寫
const pluginName = 'ConsoleLogOnBuildWebpackPlugin';
class ConsoleLogOnBuildWebpackPlugin {
//webpack 調(diào)用apply=>compiler
apply(compiler) {
compiler.hooks.run.tap(pluginName, compilation => {
console.log("webpack 構(gòu)建過程開始!");
});
}
}
// 1.類插件 apply方法
// 2.apply方法 compiler webpack-cli bin里運(yùn)行之后 馬上調(diào)度的第一個文件
// 3.webpack編譯過程 大權(quán) Compiler
// 4.Compiler->Compilation extends (Tapable)
// 5.為了在關(guān)鍵的時間節(jié)點(diǎn)可以觸發(fā)訂閱的的結(jié)構(gòu)
// 6.compilation->new SyncHook
// 7.webpack 運(yùn)行的時候 就把你的業(yè)務(wù)邏輯就給初期掛載了 compilation.call()
// 8.compilation掛載到了HTML-WEBPACK-PLUGIN call && tap 合適的實(shí)時機(jī)觸發(fā)插件
class HtmlAfterWebpackPlugin {
apply(compiler) {
compiler.hooks.compilation.tap(pluginName, compilation => {
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tap(pluginName, htmlPluginData => {
});
});
}
}
//https://alienzhou.github.io/webpack-internal-plugin-relation/
// https://webpack.docschina.org/contribute/writing-a-plugin/