我正在尝试创建一个Webpack插件,它将解析代码中的某个函数并用另一个函数替换它,该插件还将把新函数作为全局函数公开。
class someName {
constructor(local, domain, translationFile, options) {
}
apply(compiler) {
// exposing ngt function as a global
compiler.plugin('make', function(compilation, callback) {
var childCompiler = compilation.createChildCompiler('someNameExpose');
childCompiler.apply(new webpack.DefinePlugin({
ngt: function(singular , plural, quantity) {
return quantity == 1 ? singular : plural;
}
}));
childCompiler.runAsChild(callback);
});
// searching for the getValue function
compiler.parser.plugin(`call getValue`, function someNameHandler(expr) {
// create a function to replace getValue with
let results = 'ngt('+ expr.arguments +')';
const dep = new ConstDependency(results, expr.range);
dep.loc = expr.loc;
this.state.current.addDependency(dep);
return true;
});
}
}
module.exports = someName;
更新/重新表达
我在这里遇到一个问题,当注释掉compiler.parser.plugin('call getValue', function someNameHandler(expr) {...}
块时,ngt
函数存在于全局。
当未被注释时,我会收到错误,提示ngt未定义。
所谓“注释掉”,指的是使用/**/
符号来注释掉相关代码块。
我找到了一个解决办法,但并非最理想。目前,我导出一个匿名函数来实现所需功能。
您可以在这里查看该插件:Github
reactjs
标签有什么关联?是使用webpack1还是2?(对专家来说可能显而易见,但最好明确说明一下)你能否重新表述最后两个句子,加入更多细节?(抱歉,也许只是我自己的问题,但我很难理解问题在哪里) - Hugues M.