乐闻世界logo
搜索文章和话题

How to develop a Vite plugin? What are the common hook functions?

2月19日 19:15

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:

javascript
export 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:

  1. config: Modify Vite configuration, called after config resolution
  2. configResolved: Called after configuration is resolved
  3. configureServer: Configure dev server, can add middleware
  4. resolveId: Custom module resolution logic
  5. load: Custom module loading logic
  6. transform: Transform code content (most commonly used)
  7. buildStart/buildEnd: Called at build start/end
  8. 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 logic
  • configureServer: Configure dev server
  • transformIndexHtml: Transform HTML files

Plugin Example:

javascript
export 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:

javascript
import myPlugin from './my-plugin' export default { plugins: [myPlugin()] }

Best Practices:

  • Plugins should have clear naming and documentation
  • Use enforce option to control plugin execution order (pre, post)
  • Only process target files, avoid unnecessary transformations
  • Provide reasonable default configurations and options
标签:Vite