← 返回
未分类 中文

Vite Plugin Development

Use when developing Vite plugins: scaffolding plugin structure, implementing hooks (transform, resolveId, load, buildStart, etc.), handling virtual modules,...
在开发 Vite 插件时使用:脚手架插件结构、实现钩子(transform、resolveId、load、buildStart 等)、处理虚拟模块、...
goldath goldath 来源
未分类 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 343
下载
💾 0
安装
1
版本
#latest

概述

Vite Plugin Development

When to Use

  • Building a custom Vite plugin from scratch
  • Implementing transform/resolve hooks for special file types
  • Creating virtual modules or runtime injections
  • Adding HMR (Hot Module Replacement) support
  • Making plugins SSR-compatible
  • Publishing a plugin package to npm

Core Workflow

1. Plugin Scaffold

Every Vite plugin is a factory function returning a plugin object:

import type { Plugin } from 'vite'

export interface MyPluginOptions {
  include?: string | RegExp | (string | RegExp)[]
  exclude?: string | RegExp | (string | RegExp)[]
}

export default function myPlugin(options: MyPluginOptions = {}): Plugin {
  return {
    name: 'vite-plugin-my',          // required, unique name
    enforce: 'pre',                   // 'pre' | 'post' | undefined
    apply: 'build',                   // 'build' | 'serve' | ((config, env) => bool)

    // lifecycle hooks below...
  }
}

2. Key Hooks

HookPhasePurpose
----------------------
configBothModify resolved config
configResolvedBothRead final config
buildStartBothInitialize plugin state
resolveIdBothCustom module resolution
loadBothCustom module content
transformBothCode transformation
generateBundleBuildPost-process output
configureServerServeExtend dev server
handleHotUpdateServeCustom HMR logic

3. Transform Hook Pattern

transform(code, id) {
  if (!id.endsWith('.myext')) return null  // return null = skip
  const transformed = doTransform(code)
  return {
    code: transformed,
    map: null,  // provide sourcemap when possible
  }
},

4. Virtual Modules

const VIRTUAL_ID = 'virtual:my-module'
const RESOLVED_ID = '\0' + VIRTUAL_ID   // prefix \0 to avoid collisions

resolveId(id) {
  if (id === VIRTUAL_ID) return RESOLVED_ID
},
load(id) {
  if (id === RESOLVED_ID) {
    return `export const data = ${JSON.stringify(myData)}`
  }
},

5. HMR Support

handleHotUpdate({ file, server }) {
  if (file.endsWith('.myext')) {
    server.ws.send({ type: 'full-reload' })
    return []  // prevent default HMR
  }
},

6. SSR Compatibility Checklist

  • Check options.ssr in transform / load hooks
  • Avoid browser-only APIs at transform time
  • Mark side-effect-free modules: set moduleSideEffects: false
  • Test with vite build --ssr

7. Testing Strategy

// Use vite's createServer for integration tests
import { createServer } from 'vite'
const server = await createServer({ plugins: [myPlugin()] })
const mod = await server.ssrLoadModule('/src/test.myext')

Publishing Checklist

  • [ ] package.json main + module + types fields set
  • [ ] peerDependencies: "vite": "^5.0.0 || ^6.0.0"
  • [ ] README with usage example + options table
  • [ ] Export TypeScript types
  • [ ] Test against Vite 5 and 6
  • [ ] vite-plugin- prefix in package name (ecosystem convention)

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-05-07 17:48 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

office-efficiency

中文周报日报自动生成

goldath
自动从要点输入生成专业的周/日工作报告。适用于需要将原始任务笔记整理成精炼的周报/日报的场景。
★ 0 📥 620
dev-programming

Github

steipete
使用 `gh` CLI 与 GitHub 交互,通过 `gh issue`、`gh pr`、`gh run` 和 `gh api` 管理议题、PR、CI 运行及高级查询。
★ 686 📥 331,172
dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 198 📥 68,246