从WebPack 4插件通过AST更改模块的源代码

从WebPack 4插件通过AST更改模块的源代码,webpack,plugins,abstract-syntax-tree,webpack-4,Webpack,Plugins,Abstract Syntax Tree,Webpack 4,我有以下JS文件: // hello-foo.js console.log('foo') 我想用webpack将“foo”替换为“bar”。我有以下用于此目的的网页包插件: class MyPlugin { constructor() {} apply(compiler) { compiler .hooks .compilation .tap('MyPlugin', (compilation, {normalModuleFactory})

我有以下JS文件:

// hello-foo.js
console.log('foo')
我想用webpack将“foo”替换为“bar”。我有以下用于此目的的网页包插件:

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 :(

              })

          })

      })
  }
}
我进行了调试,它得到了更新后的AST,但在发出包时被忽略了

我知道对于上面这个简单的例子,加载程序可能是一个更好的选择,但如果可能的话,我对重用WebPack的AST特别感兴趣。换句话说,我不想先用Babel解析模块,然后再用WebPack/Acorn重新解析

这里已经有一个类似的,但我相信它与早期版本的WebPack有关