Rap*_*ara 9 parsing abstract-syntax-tree webpack webpack-plugin
最近,我开始学习如何构建webpack插件.我正在尝试构建一个可以更新源代码的插件.
规则很简单:
aS,我要所有的变量命名haha,以hehe在上述的大块所有模块的入口点.aS,我要所有的变量命名haha到hoho所有模块中说的块入口点.这是我的代码:
a.js
const haha = 'hello';
// will be "const hehe = 'hello';" in the bundle of "aa" entry point
// will be "const hoho = 'hello';" in the bundle of "aaaa" entry point
console.log(haha);
// will be "console.log(hehe);" in the bundle of "aa" entry point
// will be "console.log(hoho);" in the bundle of "aaaa" entry point
export default haha;
// will be "export default hehe;" in the bundle of "aa" entry point
// will be "export default hoho;" in the bundle of "aaaa" entry point
Run Code Online (Sandbox Code Playgroud)
few.js
import haha from 'a'; // will be "import hehe from 'a';" in the bundle
console.log(haha); // will be "console.log(hehe);" in the bundle
Run Code Online (Sandbox Code Playgroud)
lots.js
import haha from 'a'; // will be "import hoho from 'a';" in the bundle
console.log(haha); // will be "console.log(hoho);" in the bundle
Run Code Online (Sandbox Code Playgroud)
webpack.config.js
module.exports = {
mode: 'development',
entry: {
aa: 'few.js',
aaaa: 'lots.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
};
Run Code Online (Sandbox Code Playgroud)
我不知道到底是做什么的正确方法.
一开始,我认为我的插件必须注册到解析器的特定钩子,检查当前入口点的名称并替换AST节点的名称.问题是模块a.js只被解析一次.
我尝试的第二种方法是通过简单的正则表达式注册和重命名变量的render钩子mainTemplate.我不喜欢这种方法,因为通过正则表达式替换代码非常困难(IMO).
你怎么看?什么是正确的方法?