0

I'm working on a plugin for webpack version 4, and I'm trying to access the parser to do some pre-processing of input files, but I'm having a really hard time following the "documentation" of the new Tapable API and how I should be accessing the parser.

So far I have this:

const MY_PLUGIN_NAME = "FooPlugin";
function Plugin() {
}
Plugin.prototype.apply = function(compiler) {
    compiler.hooks.normalModuleFactory.tap(MY_PLUGIN_NAME, function(factory) {
        console.log('Got my factory here ', factory); // This is invoked as expected.
        factory.hooks.parser.tap("varDeclaration", MY_PLUGIN_NAME, function() {
            console.log('parser varDeclaration', arguments); // This is the line that's never invoked
        }
    }
}

I've tried various other parameters to the parser.tap function, nothing has seemed to help. Am I doing something wrong with how to access the parser's hooks?

austinbruch
  • 323
  • 2
  • 14

1 Answers1

2

Take an inspiration from UseStrictPlugin, it attaches to the parser and adds use strict; statement.

apply(compiler) {
    compiler.hooks.compilation.tap(
        "YouPluginName",
        (compilation, { normalModuleFactory }) => {
            const handler = parser => {
                parser.hooks.program.tap("YouPluginName", ast => {
                // -------------^ the type of parser hook
                // your code goes here
                });
            };

            normalModuleFactory.hooks.parser
                .for("javascript/auto")
                .tap("UseStrictPlugin", handler);
            normalModuleFactory.hooks.parser
                .for("javascript/dynamic")
                .tap("UseStrictPlugin", handler);
            normalModuleFactory.hooks.parser
                .for("javascript/esm")
                .tap("UseStrictPlugin", handler);
        }
    );
}
felixmosh
  • 32,615
  • 9
  • 69
  • 88
  • Thanks for this pointer, this has gotten me past my problem. Looks like the missing piece was the key into the HookMap, e.g. `javascript/auto`, `javascript/dynamic`, `javascript/esm`. How would I have known to use those? – austinbruch May 25 '18 at 15:08
  • 2
    Probably documentation should be updated... you can contribute now :] – felixmosh May 25 '18 at 15:09