在构建被封存之前,webpack会暴露依赖树吗?我搜索了整个编译器实例,但没有找到任何关于依赖树的信息。似乎应该有一个隐藏在该对象中的某个地方,因为为了稍后输出stats.json,webpack必须知道这棵树是什么。
我试过使用dependency-tree npm包,但它不支持我的webpack配置中的一些内容,所以树是不完整的。
发布于 2018-06-08 16:17:14
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()
]
}有关更多详细信息,请参阅下面的说明。
我们要找的钩子
我们可以使用finishModules编译钩子访问预先密封的依赖关系树。
我们怎么知道呢?
因为webpack钩子文档非常小(至少可以这么说),所以我们必须阅读webpack的源代码,以确保它是我们正在寻找的:
在封闭依赖树之前,编译器做的最后一件事就是“完成”它。
完成依赖关系树为编译提供了一个钩子。
代码示例
我们创建一个名为AccessDependenciesPlugin的插件
// Basic webpack plugin structure
class AccessDependenciesPlugin {
apply (compiler) {
}
}要使用编译钩子,我们需要首先访问compilation对象。我们使用compilation钩子来做这件事:
class AccessDependenciesPlugin {
apply (compiler) {
compiler.hooks.compilation.tap('AccessDependenciesPlugin', compilation => {
// We have access to the compilation now!
})
}
}现在我们点击compilation的finishModules钩子
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!
})
})
}
}钩子的modules参数是一个由webpack模块组成的数组,这些模块具有它们的依赖关系以及基本上所有其他可用的数据。
最后但同样重要的是,我们需要将插件添加到我们的webpack配置中:
module.exports = {
plugins: [
new AccessDependenciesPlugin()
]
}我们就完事了。
希望这能有所帮助。
奖励内容: webpack 3
评论中的每个请求:这是webpack 3的遗留插件系统的AccessDependenciesPlugin版本。
class AccessDependenciesPlugin {
apply (compiler) {
compiler.plugin('compilation', compilation => {
compilation.plugin('finish-modules', modules => {
/*
|---------------------------------------------------
| Here we go, `modules` is what we're looking for!
|---------------------------------------------------
*/
})
})
}
}发布于 2018-06-08 18:27:27
也许this GitHub thread的这行代码会帮你解决这个问题:
“使用webpack --profile --json > stats.json编译
(node.js接口:{ profile: true }和stats.toJson())
转到http://webpack.github.io/analyse/#modules
加载你的统计文件(它不是上传的,分析工具是一个客户端工具)。
稍等片刻,直到图表稳定下来。“
如果这不是你需要的,那么我会研究@Loilo的答案--更复杂,但可能更多你需要的。
https://stackoverflow.com/questions/47540440
复制相似问题