Vite Plugin Development: Building Custom Transforms and Dev Tools
Vite's plugin API is a thin layer over Rollup's, extended with dev-server hooks. Understanding it unlocks the ability to build custom transforms, virtual modules, dev-server middleware, and HMR logic — without ejecting from Vite.
Plugin Anatomy: Hooks and Lifecycle
A Vite plugin is a plain object (or a factory function returning one) with a name and hook methods. Hooks run at specific points in the build/dev pipeline.
// Minimal Vite plugin structure
// A plugin is just an object with a name and hooks
export default function myPlugin(options = {}) {
return {
name: 'vite-plugin-my-plugin', // required, shown in warnings/errors
enforce: 'pre', // 'pre' | 'post' | undefined
// Called once when Vite starts
configResolved(config) {
console.log('Vite mode:', config.mode);
},
// Modify Vite config before it resolves
config(config, { command }) {
if (command === 'build') {
return { build: { sourcemap: true } };
}
},
// Transform file contents
transform(code, id) {
if (!id.endsWith('.vue')) return null; // skip non-Vue files
return { code: transformedCode, map: sourceMap };
},
// Resolve module imports to file paths
resolveId(source, importer) {
if (source === 'virtual:my-module') {
return '