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

时间:2018-08-02 17:43:46

标签: webpack plugins abstract-syntax-tree webpack-4

我有以下JS文件:

// hello-foo.js
console.log('foo')

我想用webpack将'foo'替换为'bar'。我有以下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 :(

              })

          })

      })
  }
}

我调试了webpack/lib/Parser.js,它取回了更新的AST,但是在发出捆绑包时却被忽略了。

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

这里已经有一个类似的question,但我认为它与WebPack的早期版本有关。

0 个答案:

没有答案