在 webpack-4 中通过插件访问 Parser
Access Parser via Plugin in webpack-4
我正在为 webpack 版本 4 开发一个插件,我正在尝试访问 parser 来对输入文件进行一些预处理,但我真的很难跟进"documentation" 的新 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
函数的各种其他参数,但似乎没有任何帮助。我是不是在访问解析器的钩子方面做错了什么?
从 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);
}
);
}
我正在为 webpack 版本 4 开发一个插件,我正在尝试访问 parser 来对输入文件进行一些预处理,但我真的很难跟进"documentation" 的新 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
函数的各种其他参数,但似乎没有任何帮助。我是不是在访问解析器的钩子方面做错了什么?
从 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);
}
);
}