0

我正在为 webpack 版本 4 开发一个插件,并且我正在尝试访问解析器以对输入文件进行一些预处理,但是我很难遵循新的 Tapable API 的“文档”以及我应该如何访问解析器。

到目前为止,我有这个:

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
        }
    }
}

我已经尝试了该parser.tap函数的各种其他参数,似乎没有任何帮助。我在如何访问解析器的钩子方面做错了吗?

4

1 回答 1

2

从 中获取灵感UseStrictPlugin,它附加到解析器并添加use strict;语句。

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);
        }
    );
}
于 2018-05-25T14:52:14.193 回答