我有以下 JS 文件:
// hello-foo.js
console.log('foo')
Run Code Online (Sandbox Code Playgroud)
我想用 webpack 用 'bar' 替换 'foo'。我有以下 WebPack 插件:
class MyPlugin {
constructor() {}
apply(compiler) {
compiler
.hooks
.compilation
.tap('MyPlugin', (compilation, {normalModuleFactory}) => {
normalModuleFactory
.hooks
.parser
.for('javascript/auto')
.tap('MyPlugin', (parser) => {
parser
.hooks
.program
.tap('MyPlugin', (ast, comments) => {
ast.body[0].expression.arguments[0].value = 'bar'
// ast.body[0].expression.arguments[0].raw = 'bar' // does not make any difference :(
})
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
我调试了webpack/lib/Parser.js,它取回了更新的 AST,但在发出包时它被忽略了。
我知道对于上面的简单示例,加载程序可能是更好的选择,但如果可能的话,我对重用 WebPack 的 AST 特别感兴趣。换句话说,我不想先用 Babel 解析模块,然后再用 WebPack/Acorn 重新解析它。
这里已经有一个类似的问题,但我相信它与 …