Vite 插件开发:自定义转换与开发工具构建
Vite 的插件 API 是对 Rollup API 的轻量封装,并扩展了开发服务器钩子。掌握它可以让你构建自定义转换器、虚拟模块、开发服务器中间件和 HMR 逻辑,无需脱离 Vite 生态。
插件解剖:钩子与生命周期
Vite 插件是一个普通对象(或返回该对象的工厂函数),包含 name 属性和钩子方法。钩子在构建/开发流水线的特定节点触发。
// 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 '