|
| 1 | +import type { Compiler, Module, Compilation } from 'webpack' |
| 2 | +import type { CompilerNameValues } from '../../../shared/lib/constants' |
| 3 | +import { yellow, green, blue } from '../../../lib/picocolors' |
| 4 | + |
| 5 | +const PLUGIN_NAME = 'SlowModuleDetectionPlugin' |
| 6 | + |
| 7 | +const TreeSymbols = { |
| 8 | + VERTICAL_LINE: '│ ', |
| 9 | + BRANCH: '├─ ', |
| 10 | +} as const |
| 11 | + |
| 12 | +const PATH_TRUNCATION_LENGTH = 120 |
| 13 | + |
| 14 | +// Matches node_modules paths, including pnpm-style paths |
| 15 | +const NODE_MODULES_PATH_PATTERN = /node_modules(?:\/\.pnpm)?\/(.*)/ |
| 16 | + |
| 17 | +interface ModuleBuildTimeAnalyzerOptions { |
| 18 | + compilerType: CompilerNameValues |
| 19 | + buildTimeThresholdMs: number |
| 20 | +} |
| 21 | + |
| 22 | +const getModuleIdentifier = (module: Module): string => { |
| 23 | + const debugId = module.debugId |
| 24 | + return String(debugId) |
| 25 | +} |
| 26 | + |
| 27 | +const getModuleDisplayName = (module: Module): string | undefined => { |
| 28 | + const resourcePath = |
| 29 | + 'resource' in module && typeof module.resource === 'string' |
| 30 | + ? module.resource |
| 31 | + : undefined |
| 32 | + |
| 33 | + if (!resourcePath) { |
| 34 | + return undefined |
| 35 | + } |
| 36 | + |
| 37 | + let displayPath = resourcePath.replace(process.cwd(), '.') |
| 38 | + |
| 39 | + const nodeModulesMatch = displayPath.match(NODE_MODULES_PATH_PATTERN) |
| 40 | + if (nodeModulesMatch) { |
| 41 | + return nodeModulesMatch[1] |
| 42 | + } |
| 43 | + |
| 44 | + return displayPath |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * Truncates a path to a maximum length. If the path exceeds this length, |
| 49 | + * it will be truncated in the middle and replaced with '...'. |
| 50 | + */ |
| 51 | +function truncatePath(path: string, maxLength: number): string { |
| 52 | + // If the path length is within the limit, return it as is |
| 53 | + if (path.length <= maxLength) return path |
| 54 | + |
| 55 | + // Calculate the available length for the start and end segments after accounting for '...' |
| 56 | + const availableLength = maxLength - 3 |
| 57 | + const startSegmentLength = Math.ceil(availableLength / 2) |
| 58 | + const endSegmentLength = Math.floor(availableLength / 2) |
| 59 | + |
| 60 | + // Extract the start and end segments of the path |
| 61 | + const startSegment = path.slice(0, startSegmentLength) |
| 62 | + const endSegment = path.slice(-endSegmentLength) |
| 63 | + |
| 64 | + // Return the truncated path with '...' in the middle |
| 65 | + return `${startSegment}...${endSegment}` |
| 66 | +} |
| 67 | + |
| 68 | +class ModuleBuildTimeAnalyzer { |
| 69 | + private pendingModules: Module[] = [] |
| 70 | + private modules = new Map<string, Module>() |
| 71 | + private moduleParents = new Map<Module, Module>() |
| 72 | + private moduleChildren = new Map<Module, Map<string, Module>>() |
| 73 | + private isFinalized = false |
| 74 | + private buildTimeThresholdMs: number |
| 75 | + private moduleBuildTimes = new WeakMap<Module, number>() |
| 76 | + |
| 77 | + constructor(private options: ModuleBuildTimeAnalyzerOptions) { |
| 78 | + this.buildTimeThresholdMs = options.buildTimeThresholdMs |
| 79 | + } |
| 80 | + |
| 81 | + recordModuleBuildTime(module: Module, duration: number) { |
| 82 | + // Webpack guarantees that no more modules will be built after finishModules hook is called, |
| 83 | + // where we generate the report. This check is just a defensive measure. |
| 84 | + if (this.isFinalized) { |
| 85 | + throw new Error( |
| 86 | + `Invariant (SlowModuleDetectionPlugin): Module is recorded after the report is generated. This is a Next.js internal bug.` |
| 87 | + ) |
| 88 | + } |
| 89 | + |
| 90 | + if (duration < this.buildTimeThresholdMs) { |
| 91 | + return // Skip fast modules |
| 92 | + } |
| 93 | + |
| 94 | + this.moduleBuildTimes.set(module, duration) |
| 95 | + this.pendingModules.push(module) |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * For each slow module, traverses up the dependency chain to find all ancestor modules. |
| 100 | + * Builds a directed graph where: |
| 101 | + * 1. Each slow module and its ancestors become nodes |
| 102 | + * 2. Edges represent "imported by" relationships |
| 103 | + * 3. Root nodes are entry points with no parents |
| 104 | + * |
| 105 | + * The resulting graph allows us to visualize the import chains that led to slow builds. |
| 106 | + */ |
| 107 | + private prepareReport(compilation: Compilation) { |
| 108 | + for (const module of this.pendingModules) { |
| 109 | + const chain = new Set<Module>() |
| 110 | + |
| 111 | + // Walk up the module graph until we hit a root module (no issuer) to populate the chain |
| 112 | + { |
| 113 | + let currentModule = module |
| 114 | + chain.add(currentModule) |
| 115 | + while (true) { |
| 116 | + const issuerModule = compilation.moduleGraph.getIssuer(currentModule) |
| 117 | + if (!issuerModule) break |
| 118 | + if (chain.has(issuerModule)) { |
| 119 | + throw new Error( |
| 120 | + `Invariant (SlowModuleDetectionPlugin): Circular dependency detected in module graph. This is a Next.js internal bug.` |
| 121 | + ) |
| 122 | + } |
| 123 | + chain.add(issuerModule) |
| 124 | + currentModule = issuerModule |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + // Add all visited modules to our graph and create parent-child relationships |
| 129 | + let previousModule: Module | null = null |
| 130 | + for (const currentModule of chain) { |
| 131 | + const moduleId = getModuleIdentifier(currentModule) |
| 132 | + if (!this.modules.has(moduleId)) { |
| 133 | + this.modules.set(moduleId, currentModule) |
| 134 | + } |
| 135 | + |
| 136 | + if (previousModule) { |
| 137 | + this.moduleParents.set(previousModule, currentModule) |
| 138 | + |
| 139 | + let parentChildren = this.moduleChildren.get(currentModule) |
| 140 | + if (!parentChildren) { |
| 141 | + parentChildren = new Map() |
| 142 | + this.moduleChildren.set(currentModule, parentChildren) |
| 143 | + } |
| 144 | + parentChildren.set( |
| 145 | + getModuleIdentifier(previousModule), |
| 146 | + previousModule |
| 147 | + ) |
| 148 | + } |
| 149 | + |
| 150 | + previousModule = currentModule |
| 151 | + } |
| 152 | + } |
| 153 | + this.isFinalized = true |
| 154 | + } |
| 155 | + |
| 156 | + generateReport(compilation: Compilation) { |
| 157 | + if (!this.isFinalized) { |
| 158 | + this.prepareReport(compilation) |
| 159 | + } |
| 160 | + |
| 161 | + // Find root modules (those with no parents) |
| 162 | + const rootModules = [...this.modules.values()].filter( |
| 163 | + (node) => !this.moduleParents.has(node) |
| 164 | + ) |
| 165 | + |
| 166 | + const formatModuleNode = (node: Module, depth: number): string => { |
| 167 | + const moduleName = getModuleDisplayName(node) || '' |
| 168 | + |
| 169 | + if (!moduleName) { |
| 170 | + return formatChildModules(node, depth) |
| 171 | + } |
| 172 | + |
| 173 | + const prefix = |
| 174 | + ' ' + TreeSymbols.VERTICAL_LINE.repeat(depth) + TreeSymbols.BRANCH |
| 175 | + |
| 176 | + const moduleText = blue( |
| 177 | + truncatePath(moduleName, PATH_TRUNCATION_LENGTH - prefix.length) |
| 178 | + ) |
| 179 | + |
| 180 | + const buildTimeMs = this.moduleBuildTimes.get(node) |
| 181 | + const duration = buildTimeMs |
| 182 | + ? yellow(` (${Math.ceil(buildTimeMs)}ms)`) |
| 183 | + : '' |
| 184 | + |
| 185 | + return ( |
| 186 | + prefix + |
| 187 | + moduleText + |
| 188 | + duration + |
| 189 | + '\n' + |
| 190 | + formatChildModules(node, depth + 1) |
| 191 | + ) |
| 192 | + } |
| 193 | + |
| 194 | + const formatChildModules = (node: Module, depth: number): string => { |
| 195 | + const children = this.moduleChildren.get(node) |
| 196 | + if (!children) return '' |
| 197 | + |
| 198 | + return [...children] |
| 199 | + .map(([_, child]) => formatModuleNode(child, depth)) |
| 200 | + .join('') |
| 201 | + } |
| 202 | + |
| 203 | + const report = rootModules.map((root) => formatModuleNode(root, 0)).join('') |
| 204 | + |
| 205 | + if (report) { |
| 206 | + console.log( |
| 207 | + green( |
| 208 | + `🐌 Detected slow modules while compiling ${this.options.compilerType}:` |
| 209 | + ) + |
| 210 | + '\n' + |
| 211 | + report |
| 212 | + ) |
| 213 | + } |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +export default class SlowModuleDetectionPlugin { |
| 218 | + constructor(private options: ModuleBuildTimeAnalyzerOptions) {} |
| 219 | + |
| 220 | + apply = (compiler: Compiler) => { |
| 221 | + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { |
| 222 | + const analyzer = new ModuleBuildTimeAnalyzer(this.options) |
| 223 | + const moduleBuildStartTimes = new WeakMap<Module, number>() |
| 224 | + |
| 225 | + compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => { |
| 226 | + moduleBuildStartTimes.set(module, performance.now()) |
| 227 | + }) |
| 228 | + |
| 229 | + compilation.hooks.succeedModule.tap(PLUGIN_NAME, (module) => { |
| 230 | + const startTime = moduleBuildStartTimes.get(module) |
| 231 | + if (!startTime) { |
| 232 | + throw new Error( |
| 233 | + `Invariant (SlowModuleDetectionPlugin): Unable to find the start time for a module build. This is a Next.js internal bug.` |
| 234 | + ) |
| 235 | + } |
| 236 | + analyzer.recordModuleBuildTime(module, performance.now() - startTime) |
| 237 | + }) |
| 238 | + |
| 239 | + compilation.hooks.finishModules.tap(PLUGIN_NAME, () => { |
| 240 | + analyzer.generateReport(compilation) |
| 241 | + }) |
| 242 | + }) |
| 243 | + } |
| 244 | +} |
0 commit comments