|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import type {Compiler} from 'webpack'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Custom webpack plugin that forces garbage collection every 5 compilations |
| 6 | + * and logs memory usage to help monitor memory consumption during development. |
| 7 | + * |
| 8 | + * Note: Requires Node.js to be started with --expose-gc flag to enable garbage collection. |
| 9 | + */ |
| 10 | +class ForceGarbageCollectionPlugin { |
| 11 | + private compilationCount = 0; |
| 12 | + |
| 13 | + apply(compiler: Compiler) { |
| 14 | + if (gc && typeof gc === 'function') { |
| 15 | + compiler.hooks.done.tap(this.constructor.name, () => { |
| 16 | + this.compilationCount++; |
| 17 | + |
| 18 | + // Log memory usage every compilation |
| 19 | + const memUsage = process.memoryUsage(); |
| 20 | + const heapUsedMB = Math.round(memUsage.heapUsed / 1024 / 1024); |
| 21 | + const heapTotalMB = Math.round(memUsage.heapTotal / 1024 / 1024); |
| 22 | + |
| 23 | + console.log(`📊 Compilation #${this.compilationCount} - Heap: ${heapUsedMB}MB/${heapTotalMB}MB`); |
| 24 | + if (this.compilationCount % 5 === 0) { |
| 25 | + console.log(`🗑️ Forcing garbage collection after ${this.compilationCount} compilations`); |
| 26 | + // @ts-expect-error - gc is a global function provided when Node.js is started with --expose-gc flag |
| 27 | + gc(); |
| 28 | + |
| 29 | + // Log memory after garbage collection |
| 30 | + const memAfterGC = process.memoryUsage(); |
| 31 | + const heapAfterMB = Math.round(memAfterGC.heapUsed / 1024 / 1024); |
| 32 | + console.log(`✅ Post-GC heap size: ${heapAfterMB}MB (freed ${heapUsedMB - heapAfterMB}MB)`); |
| 33 | + } |
| 34 | + }); |
| 35 | + } else { |
| 36 | + console.warn('⚠️ ForceGarbageCollectionPlugin: gc() function not available. Start Node.js with --expose-gc flag to enable garbage collection.'); |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +export default ForceGarbageCollectionPlugin; |
0 commit comments