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构建上下文的信息
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 调用apply=>compiler
apply(compiler) {
compiler.hooks.run.tap(pluginName, compilation => {
console.log("webpack 构建过程开始!");
});
}
}
// 1.类插件 apply方法
// 2.apply方法 compiler webpack-cli bin里运行之后 马上调度的第一个文件
// 3.webpack编译过程 大权 Compiler
// 4.Compiler->Compilation extends (Tapable)
// 5.为了在关键的时间节点可以触发订阅的的结构
// 6.compilation->new SyncHook
// 7.webpack 运行的时候 就把你的业务逻辑就给初期挂载了 compilation.call()
// 8.compilation挂载到了HTML-WEBPACK-PLUGIN call && tap 合适的实时机触发插件
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/
网友评论