Tracing Vite plugin hooks in development and builds
Use a TypeScript tracer to inspect Vite configuration hooks, request-time transforms, HMR, and bundle output in Vite 7 and Vite 8.
Vite can run the same plugin on a browser’s module request and during a production build. I wrote a small tracer to see which hooks actually run in each environment and where their order affects the result.
One plugin interface across two execution paths
Vite 7 serves native ESM on demand in development and uses esbuild for dependency pre-bundling. Its production pipeline uses Rollup to traverse the reachable module graph, split chunks, and remove unused exports. A separate plugin API for each path would make transforms harder to reuse. Vite instead extends the bundler’s hooks with entry HTML, configuration, and server hooks.
An ordinary hook such as transform sees one module at a time. It does not need a browser connection even when a development request triggered it. Server hooks work on process state such as Connect middleware, the watcher, or WebSocket messages. Keep shared module work in the shared hooks so it also reaches production. Vite Plugin API
Configuration, server, and bundling hooks
flowchart TD
subgraph ConfigHooks["Configuration"]
H_config["config(config, env)<br/>Merge defaults"]
H_configResolved["configResolved(resolvedConfig)<br/>Read final settings"]
H_config --> H_configResolved
end
subgraph DevHooks["Vite server hooks"]
H_configureServer["configureServer(server)<br/>Add middleware"]
H_configurePreview["configurePreviewServer(server)<br/>Add preview middleware"]
H_handleHotUpdate["handleHotUpdate(ctx)<br/>Handle hot updates"]
end
subgraph BuildHooks["Module and output pipeline"]
H_options["options(opts)<br/>Adjust options"]
H_buildStart["buildStart(opts)<br/>Initialize build"]
H_resolveId["resolveId(source, importer)<br/>Resolve module ID"]
H_load["load(id)<br/>Load source"]
H_transform["transform(code, id)<br/>Transform source"]
H_transformIndexHtml["transformIndexHtml(html, ctx)<br/>Transform entry HTML"]
H_generateBundle["generateBundle(opts, bundle)<br/>Inspect output"]
H_closeBundle["closeBundle()<br/>Release resources"]
H_options --> H_buildStart --> H_resolveId --> H_load --> H_transform --> H_transformIndexHtml --> H_generateBundle --> H_closeBundle
end
H_configResolved --> H_configureServer
H_configResolved --> H_options
config(config, env)reads the user configuration and can return a partial object for Vite to merge. Check the command or mode here when your defaults depend on the environment.configResolved(resolvedConfig)sees the final configuration. I store a reference inside the plugin factory when later hooks need to read it.configureServer(server)gives the plugin the dev server and its middleware, watcher, and hot-update transport.configurePreviewServerhas a separate preview lifecycle.handleHotUpdate(ctx)inspects a change and can narrow the modules sent to the client or emit a custom event.resolveIdfinds the internal ID for an import.loadsupplies the source for that ID.transformreceives the loaded module source. The virtual module example uses the first two to provide a source without a file. Build metadata as a virtual moduletransformIndexHtmlacts on Vite’s HTML entry processing. Output hooks such asgenerateBundlesee generated chunks and assets in a build.
Controlling plugin order and activation
1
2
3
4
5
6
// plugins/types.ts
export interface Plugin {
name: string;
enforce?: 'pre' | 'post';
// ...
}
Vite places its alias handling first. User plugins marked enforce: 'pre' run before Vite’s core plugins. Normal user plugins run after the core plugins, while enforce: 'post' places a plugin after Vite’s build plugins. A lint or source-generation plugin may need the early placement. A bundle analyzer needs output that already exists. Some individual hooks also define their own ordering option, so use the hook and plugin settings appropriate to the operation.
1
2
3
4
5
6
7
8
9
10
// Enable for Vite dev
apply: 'serve'
// Enable for Vite builds
apply: 'build'
// Evaluate a predicate
apply(config, { command, mode }) {
return command === 'build' && mode === 'production';
}
apply: 'serve' limits a plugin to the serving command. apply: 'build' limits it to builds. A function can inspect a combination of command, mode, and configuration. Restrict development mocks to the server so they do not become a dependency of production bundling.
Tracing the actual calls
I added timestamps and duration logs to locate slow hooks and understood the output before adding real transformation logic. Returning null from a module hook lets the next plugin or Vite handle the source. The tracer can therefore observe resolution and loading without taking ownership of them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// plugins/vite-plugin-lifecycle-tracer.ts
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite';
interface TracerOptions {
verbose?: boolean;
}
export function lifecycleTracerPlugin(options: TracerOptions = {}): Plugin {
let resolvedConfig: ResolvedConfig;
const startTime = Date.now();
const log = (hookName: string, detail: string) => {
const elapsed = Date.now() - startTime;
const timeStr = new Date().toTimeString().split(' ')[0] + '.' + String(elapsed % 1000).padStart(3, '0');
console.log(`\x1b[90m[${timeStr}]\x1b[0m \x1b[34m[${hookName}]\x1b[0m ${detail}`);
};
return {
name: 'vite-plugin-lifecycle-tracer',
enforce: 'pre',
// 1. Configuration hooks
config(userConfig, env) {
log('config', `Hook triggered (mode: ${env.mode}, command: ${env.command})`);
return {
define: {
__LIFECYCLE_DEBUG__: true,
},
};
},
configResolved(config) {
resolvedConfig = config;
log('configResolved', `Config finalized (root: ${config.root}, mode: ${config.mode})`);
},
// 2. Development server hooks
configureServer(server: ViteDevServer) {
log('configureServer', 'HTTP DevServer & Connect middleware attached');
// Log after registering internal middleware
server.httpServer?.once('listening', () => {
log('server:ready', `Dev server listening (base: ${resolvedConfig.base})`);
});
},
handleHotUpdate(ctx) {
log('handleHotUpdate', `File changed: ${ctx.file} (${ctx.modules.length} modules affected)`);
return ctx.modules;
},
// 3. Shared Rollup hooks
options(rollupOptions) {
log('options', `Rollup options received (input: ${JSON.stringify(rollupOptions.input || 'index.html')})`);
return rollupOptions;
},
buildStart(options) {
log('buildStart', 'Build context initialized');
},
resolveId(source, importer) {
if (source.startsWith('/src/main') || source === 'index.html') {
log('resolveId', `Resolving ${source} from ${importer || 'entry'}`);
}
return null; // Let the next resolver handle it
},
load(id) {
if (id.includes('/src/main.ts')) {
log('load', `Loading module source: ${id}`);
}
return null; // Let the next loader handle it
},
transform(code, id) {
if (id.includes('/src/main.ts')) {
log('transform', `Transforming ${id} (${code.length} bytes)`);
}
return null;
},
transformIndexHtml(html) {
log('transformIndexHtml', 'Injecting metadata into index.html');
return html;
},
buildEnd() {
log('buildEnd', 'Build phase completed');
},
closeBundle() {
log('closeBundle', 'Output bundle written successfully');
},
};
}
Register the plugin in vite.config.ts.
1
2
3
4
5
6
7
8
9
// vite.config.ts
import { defineConfig } from 'vite';
import { lifecycleTracerPlugin } from './plugins/vite-plugin-lifecycle-tracer';
export default defineConfig({
plugins: [
lifecycleTracerPlugin({ verbose: true }),
],
});
Comparing the server and build traces
Figure 1. Startup hooks precede browser-driven module requests.
Start npm run dev and open http://localhost:5173/. The trace shows config, configResolved, and the server or build-container setup. Processing the entry HTML invokes transformIndexHtml. The subsequent request for /src/main.ts triggers module hooks on demand. Editing a file exercises the hot-update path without bundling the entire app.
Figure 2. The production build traverses the module graph and runs output hooks.
With npm run build, resolution and transformation follow imports from the entry points. renderChunk and generateBundle appear during output processing. closeBundle is a place to release resources, and may also run when the dev server closes its plugin container. Precise timing can vary with version and plugin mix. The trace is more reliable than assuming all hooks run in one global sequence.
Moving the tracer from Vite 7 to Vite 8
Vite 7’s default production builder is Rollup. Its transitional rolldown-vite package let projects exercise the new engine early. In Vite 8, Rolldown is the default builder and build.rolldownOptions is the preferred configuration entry. Vite accepts many familiar hooks, including resolveId, load, and transform. Check a plugin’s less common hooks and context helpers against the migration guide before relying on exact compatibility. Vite migration from v7
Rolldown uses Rust and Oxc internally. JavaScript hooks can still cross into Node frequently on a large graph. Filter by extension or path early, avoid expensive I/O in config and buildStart, and keep cached state inside the plugin instance. Confirm that cache invalidation works across repeated requests and edits.
- Log the effective command, mode, and version with any measurements.
- Compare a development request, an HMR edit, and a production build.
- Capture warnings and errors through the plugin context where the hook supports
this.warn()orthis.error(). - Confirm that a stateful plugin cleans up or invalidates its state on server restart and build close.