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?
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);
}
);
}