Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack plugin to replace a function with another

I am trying to create a webpack plugin, that will parse the code for a certain function and replace it with another function, that plugin will also expose the new function as a global.

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;

update / rephrase

I have an issue here, when compiler.parser.plugin('call getValue', function someNameHandler(expr) {...} block is commented the ngt function exist as a global.

when its not commented, i get an error, ngt is undefined.

commented i mean /**/

I found a workaround for that but its far then idea. right now what I do is I export an anonymous function that does what i want.

You can see the plugin here: Github

like image 955
Neta Meta Avatar asked Jun 01 '17 22:06

Neta Meta


1 Answers

You can override the method based on environment. Let's say you have a method

function a(){
  //original defination
}

Now based on the environment, if it's a production you could do something like this

if (environment.production) {
   function a(){
     //overridden defination
   }
}
like image 130
Rohit Goyal Avatar answered Sep 28 '22 06:09

Rohit Goyal