Vite provides a rich plugin system that allows developers to extend Vite's functionality. Here are the key points of Vite plugin development:
Basic Plugin Structure:
A Vite plugin is an object containing a name property and various hook functions:
javascriptexport default function myPlugin() { return { name: 'my-plugin', // Hook functions config(config) { // Modify configuration }, resolveId(source) { // Resolve module ID }, load(id) { // Load module content }, transform(code, id) { // Transform code } } }
Common Hook Functions:
- config: Modify Vite configuration, called after config resolution
- configResolved: Called after configuration is resolved
- configureServer: Configure dev server, can add middleware
- resolveId: Custom module resolution logic
- load: Custom module loading logic
- transform: Transform code content (most commonly used)
- buildStart/buildEnd: Called at build start/end
- generateBundle: Called when generating bundle
Rollup Plugin Compatibility:
Vite plugins are compatible with Rollup plugins. Most Rollup plugins can be used directly in Vite. However, note:
- Vite plugins run in both development and production environments
- Some Rollup-specific hooks only work in production
Development Environment Specific Hooks:
handleHotUpdate: Custom HMR update logicconfigureServer: Configure dev servertransformIndexHtml: Transform HTML files
Plugin Example:
javascriptexport default function myTransformPlugin() { return { name: 'my-transform', transform(code, id) { if (id.endsWith('.js')) { return code.replace(/foo/g, 'bar') } } } }
Plugin Configuration:
Use plugins in vite.config.js:
javascriptimport myPlugin from './my-plugin' export default { plugins: [myPlugin()] }
Best Practices:
- Plugins should have clear naming and documentation
- Use
enforceoption to control plugin execution order (pre,post) - Only process target files, avoid unnecessary transformations
- Provide reasonable default configurations and options