Skip to content

Instantly share code, notes, and snippets.

@noyobo
Last active November 7, 2023 08:05
Show Gist options
  • Save noyobo/6895fabfacb4c829792e5672f829ef03 to your computer and use it in GitHub Desktop.
Save noyobo/6895fabfacb4c829792e5672f829ef03 to your computer and use it in GitHub Desktop.
Get webpack module dependencies
class MyPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
compilation.hooks.afterOptimizeDependencies.tap('MyPlugin', ( ) => {
const dependencyGraph = compilation.moduleGraph;
// 获取所有模块
const modules = compilation.modules;
// 构建模块映射表
const moduleMap = new Map();
for (const module of modules) {
moduleMap.set(module, new Set());
}
// 遍历模块,提取依赖关系
for (const module of modules) {
const dependencies = dependencyGraph.getIncomingConnections(module);
for (const dependency of dependencies) {
const dependentModule = dependency.originModule;
if (dependentModule) {
const dependentModules = moduleMap.get(module);
dependentModules.add(dependentModule);
}
}
}
// 输出文件间的依赖关系
for (const [module, dependentModules] of moduleMap.entries()) {
console.log('Module:', module.resource);
console.log('Dependencies:', Array.from(dependentModules, depModule => depModule.resource));
console.log('---');
}
});
});
}
}
module.exports = MyPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment