我可以在webpack开始构建之前获取依赖树吗?

Kev*_*Bot 15 javascript tree node.js webpack

webpack在构建密封之前是否公开依赖树?我已经搜索了整个编译器实例,但没有找到任何关于依赖树的信息.似乎应该有一个隐藏在该对象的某个地方,因为webpack必须知道这个树是什么,以便以后输出stats.json.

我已经尝试过使用dependency-treenpm包,但它不支持我在webpack配置中的一些东西,所以树不完整.

Loi*_*ilo 11

TL; DR:是的,您可以在密封之前访问依赖树.

为此,请将以下代码添加到您的webpack.config.js:

class AccessDependenciesPlugin {
  apply (compiler) {
    compiler.hooks.compilation.tap('AccessDependenciesPlugin', compilation => {
      compilation.hooks.finishModules.tap('AccessDependenciesPlugin', modules => {
        /*
        |---------------------------------------------------
        | Here we go, `modules` is what we're looking for!
        |---------------------------------------------------
        */
      })
    })
  }
}


module.exports = {
  // ...
  plugins: [
    new AccessDependenciesPlugin()
  ]
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅下面的说明.


我们正在寻找的钩子

我们可以使用finishModules编译钩子访问预先密封的依赖树.


我们怎么知道?

由于webpack hook文档非常小(至少可以说),我们必须阅读webpack源代码以确保它是我们正在寻找的:

编译器在密封依赖关系树之前做的最后一件事是"完成"它.

完成依赖树提供了编译的钩子.


代码示例

我们创建一个名为的插件AccessDependenciesPlugin:

// Basic webpack plugin structure
class AccessDependenciesPlugin {
  apply (compiler) {

  }
}
Run Code Online (Sandbox Code Playgroud)

要使用编译钩子,我们需要首先访问该compilation对象.我们用compilation钩子做到了:

class AccessDependenciesPlugin {
  apply (compiler) {
    compiler.hooks.compilation.tap('AccessDependenciesPlugin', compilation => {
      // We have access to the compilation now!
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我们挖掘finishModules的挂钩compilation:

class AccessDependenciesPlugin {
  apply (compiler) {
    compiler.hooks.compilation.tap('AccessDependenciesPlugin', compilation => {
      compilation.hooks.finishModules.tap('AccessDependenciesPlugin', modules => {
        // Here we go, `modules` is what we're looking for!
      })
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

modules钩子的参数是一个webpack模块的数组及其依赖关系,基本上所有其他可用的数据.

最后但同样重要的是,我们需要将插件添加到我们的webpack配置中:

module.exports = {
  plugins: [
    new AccessDependenciesPlugin()
  ]
}
Run Code Online (Sandbox Code Playgroud)

我们已经完成了.


希望这可以帮助.