Vite Plugins
Vite's core is small on purpose. Framework support, legacy browser builds, PWA manifests, compression, SVG components and much more come from plugins. And because Vite's plugin API extends the Rollup/Rolldown plugin interface, writing your own plugin is surprisingly easy.
Using a plugin
Install it, import it in the config, and add it to the plugins array:
npm install -D @vitejs/plugin-legacyadded 9 packages, and audited 22 packages in 3s
found 0 vulnerabilities
// vite.config.js
import { defineConfig } from 'vite';
import legacy from '@vitejs/plugin-legacy';
export default defineConfig({
plugins: [
legacy({ targets: ['defaults', 'not IE 11'] }),
],
});Most plugins are functions that return a plugin object, so you call them (legacy(...)) and can pass options.
Popular plugins
| Plugin | What it adds |
|---|---|
@vitejs/plugin-react |
React Fast Refresh + JSX |
@vitejs/plugin-vue |
Vue single-file components |
@sveltejs/vite-plugin-svelte |
Svelte components |
@vitejs/plugin-legacy |
Extra build for old browsers + polyfills |
@tailwindcss/vite |
Tailwind CSS v4 |
vite-plugin-pwa |
Service worker + web manifest |
vite-plugin-checker |
TypeScript/ESLint errors in the terminal and browser |
vite-plugin-inspect |
Shows how each plugin transformed every module |
Browse more at the community list "awesome-vite" or on npm with the vite-plugin keyword.
Writing your own plugin
A plugin is an object with a name and some hooks. Vite calls the hooks while it resolves, loads and transforms modules.
// vite.config.js
import { defineConfig } from 'vite';
function bannerPlugin(text) {
return {
name: 'banner',
transform(code, id) {
if (!id.endsWith('.js')) return null; // not our business
return { code: `/* ${text} */\n${code}`, map: null };
},
};
}
export default defineConfig({
plugins: [bannerPlugin('ExcelTAD course build')],
});The module pipeline
For every import, Vite runs three hook stages, asking each plugin in order until one answers:
| Hook | Question it answers | Return |
|---|---|---|
resolveId(source, importer) |
Which file/id does this import mean? | An id string, or null to pass |
load(id) |
What is the content of this id? | Code string, or null to read from disk |
transform(code, id) |
How should this code be changed? | New code (+ source map), or null |
The playground runs a tiny version of this pipeline with two plugins. One provides a virtual module — content that exists only in memory — and the other transforms code:
const plugins = [
{
name: 'virtual-build-info',
resolveId(source) {
if (source === 'virtual:build-info') return '\0virtual:build-info';
return null;
},
load(id) {
if (id === '\0virtual:build-info') return 'export const builtWith = "Vite";';
return null;
},
},
{
name: 'shout',
transform(code, id) {
return code.replace(/"Vite"/g, '"VITE ⚡"');
},
},
];
const disk = { '/src/main.js': 'import { builtWith } from "virtual:build-info";' };
function runHook(hook, ...args) {
for (const p of plugins) {
const result = p[hook]?.(...args);
if (result != null) return { by: p.name, result };
}
return { by: 'vite-core', result: null };
}
function processModule(source) {
const r = runHook('resolveId', source);
const id = r.result ?? source;
const l = runHook('load', id);
let code = l.result ?? disk[id];
for (const p of plugins) code = p.transform?.(code, id) ?? code;
console.log(`${source} | resolved by ${r.by} | loaded by ${l.by}`);
console.log(' ->', code);
}
processModule('/src/main.js');
processModule('virtual:build-info');/src/main.js | resolved by vite-core | loaded by vite-core
-> import { builtWith } from "virtual:build-info";
virtual:build-info | resolved by virtual-build-info | loaded by virtual-build-info
-> export const builtWith = "VITE ⚡";
Note: The
\0prefix is a convention meaning "this id is virtual, don't try to read it from disk and don't let other plugins process it as a file". In the browser you'll see it as/@id/__x00__virtual:build-info.
Vite-specific hooks
On top of the bundler hooks, Vite adds hooks that only make sense for a dev server and HTML:
| Hook | When it runs | Typical use |
|---|---|---|
config(config, env) |
Before the config is resolved | Return partial config to merge |
configResolved(config) |
After resolving | Read the final config |
configureServer(server) |
Dev server creation | Add middleware (server.middlewares.use) |
configurePreviewServer(server) |
Preview server creation | Same for vite preview |
transformIndexHtml(html) |
When serving/building HTML | Inject tags, replace text |
hotUpdate (Vite 6+) / handleHotUpdate |
A file changed | Custom HMR behaviour |
function htmlStampPlugin() {
return {
name: 'html-stamp',
transformIndexHtml(html) {
return html.replace('</head>', ' <meta name="generator" content="Vite">\n</head>');
},
configureServer(server) {
server.middlewares.use('/api/ping', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ pong: true }));
});
},
};
}Ordering and conditions
{
name: 'my-plugin',
enforce: 'pre', // 'pre' runs before core plugins, 'post' after build plugins
apply: 'build', // only during build; 'serve' = only in dev; or a function
}The effective order is: alias → enforce: 'pre' plugins → Vite core → normal plugins → Vite build plugins → enforce: 'post' plugins → post-build plugins.
const userPlugins = [
{ name: 'a' },
{ name: 'minify-html', enforce: 'post' },
{ name: 'b' },
{ name: 'raw-svg', enforce: 'pre' },
];
const rank = (p) => (p.enforce === 'pre' ? 0 : p.enforce === 'post' ? 2 : 1);
const sorted = [...userPlugins].sort((x, y) => rank(x) - rank(y)).map((p) => p.name);
console.log(sorted.join(' → '));raw-svg → a → b → minify-html
Within a group, the order in your plugins array is kept.
Tip: Install
vite-plugin-inspectand visithttp://localhost:5173/__inspect/to see each module's code after every plugin step — the best way to debug a plugin.
Test yourself
Which hook answers "what code does this id contain?"
- resolveId
- load
- transform
- configResolved
What does apply: 'serve' do?
- Applies the plugin only during the dev server
- Applies it only to builds
- Runs it before other plugins
- Serves its files from public/
Why do virtual module ids usually start with \0?
- It makes them load faster
- It marks them as virtual so they aren't read from disk or processed as files by other plugins
- It is required by browsers
- It encrypts the module