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

4

2 回答 2

1

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

function a(){
  //original defination
}

现在基于环境,如果它是一个生产你可以做这样的事情

if (environment.production) {
   function a(){
     //overridden defination
   }
}
于 2017-09-22T04:18:42.043 回答
0

你可以使用 webpack-merge 插件,它非常适合做你想做的事。

https://github.com/survivejs/webpack-merge

于 2018-05-31T06:38:51.613 回答