How do Vite plugins, hooks and virtual modules work?
AdvancedBuild tools: webpack and Vite interview questionBy UIRound, updated 21 November 2026
Short answer
A Vite plugin is an object with a name and a set of hook functions that Vite calls at fixed points. Most hooks come from Rollup's plugin interface, such as resolveId, load and transform; Vite adds its own for config, the dev server, index.html and hot updates. A virtual module is an import id that a plugin resolves and loads itself, so the code never exists as a file.
What a plugin looks like
A plugin is usually returned from a factory function, so it can take options:
// vite.config.ts
import { defineConfig, type Plugin } from "vite";
function banner(text: string): Plugin {
return {
name: "banner",
apply: "build", // only during vite build
enforce: "post", // run after normal plugins
renderChunk(code) {
return { code: `/* ${text} */\n${code}`, map: null };
},
};
}
export default defineConfig({ plugins: [banner("built by CI")] });apply limits a plugin to "serve" or "build". enforce: "pre" or "post" moves it before or after Vite's own core plugins; without it, plugins run in the order you list them, after the core resolution and alias plugins. Ordering matters most for transform, because each plugin receives the previous plugin's output.
Rollup-compatible hooks
These follow Rollup's semantics, which is why many Rollup plugins work in Vite unchanged.
buildStartandbuildEnd: run once when a build or the dev server starts and stops.resolveId(source, importer): turns an import string like"./utils"or"@/api"into a resolved id, usually an absolute path. Returnnullto let the next plugin try.load(id): returns the source for an id. Normally the file system does this; a plugin overrides it for generated code.transform(code, id): changes a module's code and returns the new code with a source map. This is where TypeScript stripping, JSX and most framework compilation happen.
Output hooks such as renderChunk, generateBundle and writeBundle only run during vite build, because the dev server never produces chunks. In dev, Vite runs a plugin container that calls the per-module hooks as the browser requests each file, which is how it serves source on demand (the dev server import rewriting problem shows the result).
If resolution is the part you want to understand deeply, implementing bundler module resolution builds it from scratch.
Vite-specific hooks
config(config, env): change the user config before it is resolved, for example to add an alias or a define.envtells you the command and mode.configResolved(resolved): read the final config, such asresolved.baseorresolved.command, and store what you need.configureServer(server): add middleware to the dev server or keep a reference to it for later. Middleware added directly runs before Vite's own; returning a function runs it after.transformIndexHtml(html): changeindex.htmlor inject tags. It runs in dev and build.handleHotUpdate(ctx): decide what happens when a file changes in dev, such as filtering the affected modules or sending a custom event over the HMR connection. Newer versions also offer an environment-aware hot update hook; check the docs for the version you use.
function healthCheck(): Plugin {
return {
name: "health-check",
configureServer(server) {
server.middlewares.use("/__health", (_req, res) => res.end("ok"));
},
transformIndexHtml() {
return [{ tag: "meta", attrs: { name: "build-time", content: new Date().toISOString() }, injectTo: "head" }];
},
};
}Virtual modules
A virtual module lets application code import something a plugin generates: build metadata, a list of routes found on disk, or config computed at build time. The convention has two parts:
- The public import id starts with
virtual:, so it is obvious in source that no file exists. - The resolved id starts with
"\0". That prefix is a Rollup convention telling other plugins (and Node-style resolution) to leave the module alone, and it keeps the id from being mistaken for a real path.
// plugins/build-info.ts
import type { Plugin } from "vite";
import { execSync } from "node:child_process";
export function buildInfo(): Plugin {
const publicId = "virtual:build-info";
const resolvedId = "\0" + publicId;
return {
name: "build-info",
resolveId(id) {
if (id === publicId) return resolvedId;
},
load(id) {
if (id !== resolvedId) return;
const commit = execSync("git rev-parse --short HEAD").toString().trim();
return `export const commit = ${JSON.stringify(commit)};\nexport const builtAt = ${JSON.stringify(new Date().toISOString())};`;
},
};
}// src/footer.tsx
import { commit, builtAt } from "virtual:build-info";TypeScript does not know about the module until you declare it:
// src/virtual.d.ts
declare module "virtual:build-info" {
export const commit: string;
export const builtAt: string;
}In the browser during development the null byte cannot appear in a URL, so Vite encodes it and serves the module under a special /@id/ path. You do not have to handle that yourself.
If the virtual module depends on files, such as a routes list built from a folder, call this.addWatchFile() in load or invalidate the module from handleHotUpdate, otherwise the dev server keeps serving the first version.
How this compares to webpack
Webpack splits the same work between loaders, which transform one file type, and plugins, which tap into compiler hooks. Vite folds both into one plugin object with transform doing what a loader does. The contrast is laid out in webpack loaders vs plugins, and building a tapable-style plugin system shows how hook systems work underneath.
Newer Vite versions are moving their bundler to Rolldown, a Rust bundler that keeps a Rollup-compatible plugin API, so plugins written against these hooks are meant to keep working.
Common follow-up questions
Can I use a Rollup plugin in Vite?
Often, yes, if it only uses hooks that make sense in dev as well as build, or if you limit it with apply: "build". Plugins that depend on output hooks or on Rollup-only options during dev will not behave the same.
Why does my transform run on files I did not expect?
transform is called for every module, including dependencies and CSS. Check the id with a regular expression or a filter and return early for anything you do not handle.
How do I share data between hooks?
Keep it in the factory function's closure. Store the resolved config in configResolved, then read it in later hooks.
Mistakes to avoid
Forgetting the
"\0"prefix on a virtual module's resolved id, so other plugins try to read it from diskReturning an empty string instead of
undefinedfromresolveIdorloadwhen the id is not yoursReturning transformed code without a source map, which breaks debugging for every later step
Doing slow work in
transformfor every file instead of filtering ids firstUsing output hooks and expecting them to run in the dev server
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Rewrite imports like the Vite dev server: bare specifiers to pre-bundled deps,
?importon assetsMedium40 min - Build a tapable-style plugin system: sync, bail, waterfall and async hooks with stages and interceptorsMedium50 min
- Implement bundler module resolution: extensions,
node_modules, packageexportsconditions and aliasesHard60 min - Build a webpack loader runner: rule matching, right-to-left loaders, pitching and async loadersMedium45 min
- Build a mini module bundler: resolve imports, build the graph, handle cycles and emit one runnable bundleHard60 min