12

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

Sagar V
  • 12,158
  • 7
  • 41
  • 68
Neta Meta
  • 4,001
  • 9
  • 42
  • 67
  • Hi, is it possible to clarify the following points? How is `reactjs` tag relevant? Is it webpack 1 or 2? (might be obvious to an expert, but better make it explicit) Could you rephrase the last 2 sentences, with more details? (sorry, might be me, but I have trouble understanding what the problem is) – Hugues M. Jun 08 '17 at 21:55
  • @Hugues Moreau it doesnt have direct relation to reactjs but it is used for reactjs, webpack 1. and i've updated the question with more details. – Neta Meta Jun 08 '17 at 22:09
  • 1
    why not write/use a babel plugin for this? its much easier and babel is after all a transpiler. – Bamieh Aug 22 '17 at 20:36

2 Answers2

1

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
   }
}
Rohit Goyal
  • 212
  • 1
  • 2
  • 8
0

You can use the webpack-merge plugin, it's very useful to do exactly what do you want.

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