ARTICLE · 1520982
深入 Vite 核心:万字长文带你彻底搞懂插件钩子机制
Vite插件实现
我们熟悉了Vite特有的钩子以及通用的钩子,此时我们来学习一下如何编写一个插件。
我们为Vue3设计一个Vite插件,自动导入组件插件,它解决了Vue3项目中反复手动导入/注册组件的痛点,无需修改代码即可自动注册全局组件,下面我们将从零开始超详细的开发步骤:
解决的问题
在 Vue3 项目中,传统使用方式:
<!-- 每个组件需要手动导入和注册 -->
<script setup>
import TheHeader from '@/components/TheHeader.vue'
import ProductCard from '@/components/ProductCard.vue'
</script>
<template>
<TheHeader />
<ProductCard />
</template>
问题1:当组件数量增多时,重复导入代码量激增。 问题2:组件重命名/移动路径时需手动修改所有导入语句 问题3:TypeScript无法自动推导出全局组件类型(需额外配置)。
本插件实现效果
<!-- 无需任何 import,直接使用组件 -->
<template>
<TheHeader /> <!-- 自动识别 src/components/TheHeader.vue -->
<ProductCard /> <!-- 自动识别 src/components/ProductCard.vue -->
</template>
插件特性
✅ Vue3 专属:完美支持 <script setup>和组合式 API✅ 零配置:默认扫描 src/components✅ 热更新:新增/删除组件时自动刷新 ✅ 类型安全:自动生成 .d.ts 类型声明 ✅ 轻量无依赖:仅 80 行核心代码
1、初始化项目
我们直接新建一个Vite + Vue3的项目,直接在该项目中做一个插件,然后来验证其效果。
在Vue3项目根目录下新建一个plugins文件夹,这里用来放插件,只是用来测试的,真实项目就不能这样去做了。
实际项目目录如下所示:
vue3-demo/
├── plugins/ # 用来开发自定义插件
├── src/ # 源代码目录
│ ├── components # 公共组件目录
│ ├── App.vue # 根组件
│ └── main.ts # 入口文件
├── package.json
└── vite.config.ts # vite.config.ts配置文件
2、设计思路
2.1、自定义插件的执行时机
Vite 将插件分为3个执行阶段(按顺序执行):
@vitejs/plugin-vue | ||
Vite通过在插件返回的对象中设置enforce: 'xxx'来设置插件的执行顺序。
那么我们这个插件执行顺序应该怎么设置呢?
我们这个插件必须设置enforce: 'pre',必须在 Vue 编译器之前注入import语句。 用户写的App.vue如下:
<template>
<div>
<Home />
<About />
</div>
</template>
<script setup lang="ts">
// 没有import导入
</script>
然后我使用autoImportComponents(enfornce: 'pre') 先执行,转换后的代码为:
<template>
<div>
<Home />
<About />
</div>
</template>
<script setup lang="ts">
import Home from './components/Home.vue'
import About from './components/About.vue'
</script>
然后在执行@vitejs/plugin-vue,将其编译成JavaScript;
如果不在@vitejs/plugin-vue插件之前执行,那么首先代码用了该插件,但是你没有引入,此时会报错。
2.2、使用Vite哪些钩子
对于要实现这个插件,要使用Vite相关哪些钩子呢,为什么要使用其中的一些钩子,我们上篇文章详细讲到Vite的一些相关钩子,下面我们先来总结一下:
Vite特有钩子(仅Vite支持)
Vite通用钩子(遵循Rollup/Rolldown插件规范)
首先这里我们需要用到的第一个钩子是 Vite的特有钩子:configResolved,这个钩子代表配置解析完成。
为啥使用这个钩子,而不是使用config、options以及其他。
2.2.1、为什么最开始使用configResolved钩子
首先,用户通过npm run dev启动阶段,执行顺序(从上到下),注意:测试用户还未打开页面。
| 1. config (config) ← 配置文件解析前
│ └─ 可以修改配置
│ 2. configResolved (configResolved) ← 配置文件解析完成 ✅
│ └─ 获取完整配置,适合初始化
│ 3. options (options) ← Rollup 配置阶段
│ └─ 配置 Rollup 选项
│ 4. buildStart (buildStart) ← 构建开始
│ └─ 构建前的准备工作
│ 5. configServer (buildStart) ← 服务器配置完成
│ └─ 设置文件监听器、中间件
此时config钩子可能太早无法获取项目的根目录,而剩下的钩子都在configResolved后面执行,太晚了,可能都开始处理文件了。
在这个钩子我们主要做三件事:
1、获取项目的根目录 2、根据根目录扫描组件 3、开发环境:生成类型声明文件
下面我们按照要做的事来实现:我们在plugins文件下新建这三个文件:
├── plugins/ # 自定义插件
│ ├── autoImportComponents # 自动导入插件
│ │ ├── index.ts # 插件的入口文件
│ │ ├── types.d.ts # 组件的类型声明文件模版,靠这个自动生成
│ │ └── utils.ts # 工具类文件,将共用文件提取出来
首先是index.ts内容:
// 这个是Vite插件的入口文件
import { resolve } from'path'
import { createRequire } from'module'
import { getRoot, scanComponents, generateTypes, type ComponentInfo, type ViteConfig } from'./utils'
// 兼容CommonJS
constrequire = createRequire(import.meta.url)
// 插件配置选项接口
export interface AutoImportComponentsOptions {
componentsDir?: string
dts?: string
}
// Vite 插件钩子类型
interface VitePlugin {
name: string
enforce?: 'pre' | 'post'
configResolved?: (config: ViteConfigResolved) =>void
transform?: (code: string, id: string) => { code: string; map: null } | undefined
configureServer?: (server: ViteDevServer) =>void
writeBundle?: () =>void
}
// Vite 已解析配置类型
interface ViteConfigResolved extends ViteConfig {
command: 'serve' | 'build'
}
/*
* 自动导入组件插件
* @param options - 配置选项
* @param options.componentsDir - 组件目录,默认 'src/components'
* @param options.dts - 生成的类型声明文件名,默认 'components.d.ts'
* @returns - 返回一个对象
* */
exportdefaultfunctionautoImportComponents(options:AutoImportComponentsOptions = {}): VitePlugin{
const { componentsDir = 'src/components', dts = 'components.d.ts' } = options;
// 项目的根目录
let root:string = "";
// 扫描到的组件列表
let components: ComponentInfo[] = []
return {
name: 'vite-plugin-auto-import-components', // 插件名字(唯一)
enforce: 'pre', // 插件执行顺序,优先执行,确保在Vue插件之前执行
// 1、配置解析阶段(关键,必须在此阶段扫描组件)
configResolved(config: any) {
// 1.1、获取根目录
root = getRoot(config);
// 1.2、根据根目录扫描组件
components = scanComponents(root, componentsDir);
// 1.3、开发环境:生成类型声明文件
if (config.command === 'serve') {
// 拼接类型声明文件路径
const dtsPath = resolve(root, dts)
// 写入类型声明文件
require('fs').writeFileSync(dtsPath, generateTypes(components), 'utf-8')
}
}
}
}
按照上面的执行顺序,接下来我们执行configureServer钩子,这个钩子里面用来监听组件的变化,为啥要用这个钩子,为啥不用options、buildStart等这些钩子:
核心原因:只有configureServer能访问到服务器实例
钩子对比表:
2.2.2、configureServer
configureServer(server: ViteDevServer) { ... }
server.watcher 是Vite开发服务器内部使用的文件监听器。
具体语法:
// eventType: 事件类型
// callback: 回调函数
server.watcher.on(eventType, callback)
事件类型列表:
all | ||
add | ||
addDir | ||
change | ||
unlink | ||
unlinkDir |
在这个钩子要做什么,一旦监听到文件的变化:
1、重新扫描组件 2、重新生成类型声明文件 3、清空所有模块缓存
exportdefaultfunctionautoImportComponents(
options: AutoImportComponentsOptions = {}
): VitePlugin{
const { componentsDir = 'src/components', dts = 'components.d.ts' } = options
let root: string = ''
let components: ComponentInfo[] = []
return {
name: 'vite-plugin-auto-import-components',
enforce: 'pre',
//...
configureServer(server: ViteDevServer) {
server.watcher.on('all', (_event: string, path: string) => {
if (path.includes(componentsDir) && path.endsWith('.vue')) {
console.log('[auto-import-components] 组件变化,重新扫描:', path)
components = scanComponents(root, componentsDir)
const dtsPath = resolve(root, dts)
require('fs').writeFileSync(dtsPath, generateTypes(components), 'utf-8')
server.moduleGraph.invalidateAll()
}
})
},
}
}
用户访问:http://localhost:5273/
浏览器请求 index.html,index.html被返回(包含<script type="module" src="/src/main.ts">).浏览器请求 main.ts。main.ts导入App.vue,会执行Vite相关钩子(resolveId钩子、load钩子、transform钩子)
我们看一下Vite插件钩子的完整执行顺序。
| 1. config (config) ← 配置文件解析前
│ └─ 可以修改配置
│ 2. configResolved (configResolved) ← 配置文件解析完成 ✅
│ └─ 获取完整配置,适合初始化
│ 3. options (options) ← Rollup 配置阶段
│ └─ 配置 Rollup 选项
│ 4. buildStart (buildStart) ← 构建开始
│ └─ 构建前的准备工作
│ 5. resolveId/load/transform ← 文件处理阶段
│ └─ 处理每个文件
│ 6. buildEnd/writeBundle ← 构建完成
│ └─ 清理工作
对于自动导入插件来说,最关键的是transform钩子:
2.2.3、transform
transform 钩子里面主要是在Vue文件的<script setup>标签后自动注入组件的import语句。
// code: 文件的源代码
// id:文件的完整路径
transform(code: string, id: string) { ...}
主要代码:
transform(code: string, id: string) {
// 检查文件路径是否以.vue结尾
if (id.endsWith('.vue')) {
// 定义正则表达式,匹配<script setup ...>
const scriptSetupRegex = /<script\s+setup[^>]*>/
if (scriptSetupRegex.test(code)) {
const injectCode = components
.map((c) =>`import ${c.name} from '${c.path}'`)
.join('\n')
console.log('[auto-import-components] 注入代码到:', id)
return {
code: code.replace(scriptSetupRegex, (match) => `${match}\n${injectCode}`),
map: null
}
}
}
return { code, map: null }
},
假设components数组是:
[
{ name: "Home", path: "./components/Home.vue" },
{ name: "About", path: "./components/About.vue" }
]
生成的injectCode是:
import Home from'./components/Home.vue';
import About from'./components/About.vue'
此刻就完成了该插件所有的功能,我们来看一下全部的源码:
plugins/autoImportComponents/utils.ts
import { readFileSync, existsSync } from'fs'
import { resolve } from'path'
// 组件信息接口
export interface ComponentInfo {
name: string
path: string
}
// Vite 配置接口(简化版)
export interface ViteConfig {
root?: string
}
// 获取项目的根目录
exportconst getRoot = (config: ViteConfig): string => {
return config.root || process.cwd()
}
// 扫描组件目录
exportconst scanComponents = (
root: string,
componentsDir: string = 'src/components'
): ComponentInfo[] => {
// 组件目录的绝对路径
const dir = resolve(root, componentsDir)
// 尝试读取 index.ts 或 index.js
const tsPath = `${dir}/index.ts`
const jsPath = `${dir}/index.js`
try {
let filePath: string
if (existsSync(tsPath)) {
filePath = tsPath
} elseif (existsSync(jsPath)) {
filePath = jsPath
} else {
return []
}
return readFileSync(filePath, 'utf-8')
.split('\n')
.filter((line: string) => line.includes('export { default as'))
.map((line: string) => {
const match = line.match(/export { default as (\w+) }/)
const componentName = match ? match[1] : ''
return {
name: componentName,
path: `./components/${componentName}.vue`
}
})
.filter((component: ComponentInfo): component is ComponentInfo => component.name !== '')
} catch (error) {
console.warn('[auto-import-components] 未找到 components/index.js,将使用动态扫描')
return []
}
}
// 生成类型声明
exportconst generateTypes = (components: ComponentInfo[]): string => {
return`/* Generated by vite-plugin-auto-import-components */
declare module 'vue' {
export interface GlobalComponents {
${components.map((c) => `${c.name}: typeof import('${c.path}')['default']`).join(';\n ')}
}
}
export {};`
}
plugins/autoImportComponents/index.ts
import { resolve } from'path'
import { createRequire } from'module'
import { getRoot, scanComponents, generateTypes, type ComponentInfo, type ViteConfig } from'./utils'
constrequire = createRequire(import.meta.url)
// 插件配置选项接口
export interface AutoImportComponentsOptions {
componentsDir?: string
dts?: string
}
// Vite 插件钩子类型
interface VitePlugin {
name: string
enforce?: 'pre' | 'post'
configResolved?: (config: ViteConfigResolved) =>void
transform?: (code: string, id: string) => { code: string; map: null } | undefined
configureServer?: (server: ViteDevServer) =>void
writeBundle?: () =>void
}
// Vite 已解析配置类型
interface ViteConfigResolved extends ViteConfig {
command: 'serve' | 'build'
}
// Vite 开发服务器类型
interface ViteDevServer {
watcher: {
on: (event: string, callback: (eventType: string, path: string) =>void) => void
}
moduleGraph: {
invalidateAll: () =>void
}
}
exportdefaultfunctionautoImportComponents(
options: AutoImportComponentsOptions = {}
): VitePlugin{
const { componentsDir = 'src/components', dts = 'components.d.ts' } = options
let root: string = ''
let components: ComponentInfo[] = []
return {
name: 'vite-plugin-auto-import-components',
enforce: 'pre',
configResolved(config: ViteConfigResolved) {
root = getRoot(config)
components = scanComponents(root, componentsDir)
console.log('[auto-import-components] 扫描到的组件:', components)
if (config.command === 'serve') {
// 拼接类型声明文件路径
const dtsPath = resolve(root, dts)
// 写入类型声明文件
require('fs').writeFileSync(dtsPath, generateTypes(components), 'utf-8')
console.log('[auto-import-components] 类型声明文件已生成:', dtsPath)
}
},
transform(code: string, id: string) {
if (id.endsWith('.vue')) {
const scriptSetupRegex = /<script\s+setup[^>]*>/
if (scriptSetupRegex.test(code)) {
const injectCode = components
.map((c) =>`import ${c.name} from '${c.path}'`)
.join('\n')
console.log('[auto-import-components] 注入代码到:', id)
return {
code: code.replace(scriptSetupRegex, (match) => `${match}\n${injectCode}`),
map: null
}
}
}
return { code, map: null }
},
configureServer(server: ViteDevServer) {
server.watcher.on('all', (_event: string, path: string) => {
if (path.includes(componentsDir) && path.endsWith('.vue')) {
console.log('[auto-import-components] 组件变化,重新扫描:', path)
components = scanComponents(root, componentsDir)
const dtsPath = resolve(root, dts)
require('fs').writeFileSync(dtsPath, generateTypes(components), 'utf-8')
server.moduleGraph.invalidateAll()
}
})
},
writeBundle() {
if (dts) {
const dtsPath = resolve(root, dts)
require('fs').writeFileSync(dtsPath, generateTypes(components), 'utf-8')
console.log('[auto-import-components] 生产环境类型声明文件已生成:', dtsPath)
}
}
}
}
plugins/autoImportComponents/types.d.ts
// vite-plugin-auto-import-components/types.d.ts
/* eslint-disable */
declare module'vue' {
export interface GlobalComponents {
// 组件类型声明将由插件自动生成
[componentName: string]: any
}
}
export { };
3、项目中使用
在vite.config.ts中进行配置:
import { defineConfig } from'vite'
import vue from'@vitejs/plugin-vue'
import autoImportComponents from'./plugins/autoImportComponents'
// https://vite.dev/config/
exportdefault defineConfig({
plugins: [
vue(),
autoImportComponents({
componentsDir: 'src/components', // 组件目录(可选,默认就是 src/components)
dts: 'components.d.ts'// 生成的类型声明文件路径(可选)
})
],
})















































































