|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +import inspector from 'node:inspector'; |
| 9 | +import fs from 'fs-extra'; |
| 10 | +import type {Compiler} from 'webpack'; |
| 11 | + |
| 12 | +// Bundle CPU profiling plugin, contributed by the Rspack team |
| 13 | +// Can be opened in https://www.speedscope.app/ |
| 14 | +// See also https://github.com/jerrykingxyz/docusaurus/pull/1 |
| 15 | +// See also https://github.com/facebook/docusaurus/pull/10985 |
| 16 | +export class BundlerCPUProfilerPlugin { |
| 17 | + output: string; |
| 18 | + |
| 19 | + constructor(output?: string) { |
| 20 | + this.output = output ?? './bundler-cpu-profile.json'; |
| 21 | + } |
| 22 | + |
| 23 | + apply(compiler: Compiler): void { |
| 24 | + const session = new inspector.Session(); |
| 25 | + session.connect(); |
| 26 | + session.post('Profiler.enable'); |
| 27 | + session.post('Profiler.start'); |
| 28 | + |
| 29 | + // In dev/watch mode, we restart the profiler before each compilation |
| 30 | + compiler.hooks.watchRun.tapPromise( |
| 31 | + BundlerCPUProfilerPlugin.name, |
| 32 | + async () => { |
| 33 | + session.post('Profiler.start'); |
| 34 | + }, |
| 35 | + ); |
| 36 | + |
| 37 | + compiler.hooks.done.tapPromise(BundlerCPUProfilerPlugin.name, async () => { |
| 38 | + session.post('Profiler.stop', (error, param) => { |
| 39 | + if (error) { |
| 40 | + console.error('Failed to generate JS CPU profile:', error); |
| 41 | + return; |
| 42 | + } |
| 43 | + fs.writeFile(this.output, JSON.stringify(param.profile)).catch( |
| 44 | + console.error, |
| 45 | + ); |
| 46 | + }); |
| 47 | + }); |
| 48 | + } |
| 49 | +} |
0 commit comments