用于替换函数的webpack插件

12

我正在尝试创建一个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.
@Hugues Moreau 这与ReactJS没有直接关系,但它用于ReactJS和Webpack 1。我已经更新了问题并提供了更多细节。 - Neta Meta
1
为什么不写/使用一个Babel插件来完成这个任务呢?这样会更容易,毕竟Babel是一个转译器。 - Bamieh
2个回答

1

您可以根据环境覆盖该方法。假设您有一个方法

function a(){
  //original defination
}

根据环境不同,如果是生产环境,您可以这样做。
if (environment.production) {
   function a(){
     //overridden defination
   }
}

-1

这有什么用呢?我点击了链接,发现它是用于合并对象的。但是原帖的需求是替换一个不同的函数调用。你能否分享一段代码片段,展示一下原帖作者如何实现这个目的呢? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接