适用范围:Vite 5/6 的教学原型。将第 1–3 节代码合并到一个插件文件,并安装
npm i -D @babel/parser@7。示例仅扫描一层目录中直接声明的具名函数;没有实现按标识符使用位置自动导入,文件变化采用整页刷新。
这是一个可直接用于 Vite 的插件原型,集成了:
- ✅ 扫描 API 并生成具名导出模块
- ✅ 注入虚拟模块
virtual:env(模拟 import.meta.env) - ✅ 文件变化后失效虚拟模块并整页刷新
- ✅ 虚拟模块体系(virtual:xxx)
🌟 整体效果(最终可实现)
ts
import { useFoo, compute } from 'virtual:auto-api'
import { VITE_API_URL, MODE } from 'virtual:env'
// File changes reload the page; no self-accept handler is needed.插件能力:
自动扫描 API 文件夹(如
src/composables)自动将函数名汇总到虚拟模块,使用方仍需显式导入
生成虚拟模块:
virtual:auto-api→ 导出自动 APIvirtual:env→ 导出公开前缀变量和内置模式字段
import.meta.env保持由 Vite 处理;本文使用显式虚拟模块导入监听环境文件的新增、修改和删除,并整页刷新
📦 1. 插件整体结构
一个完整插件大概如此:
ts
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { loadEnv } from 'vite'
import { parse } from '@babel/parser'
export default function AutoAllPlugin(options = {}) {
const apiDir = options.apiDir || 'src/composables'
const apiId = '\0virtual:auto-api'
const envId = '\0virtual:env'
let config
let env = {}
const readEnv = () => ({
...loadEnv(config.mode, config.envDir, 'VITE_'),
MODE: config.mode, DEV: !config.isProduction,
PROD: config.isProduction, BASE_URL: config.base
})
return {
name: 'vite:auto-all-plugin',
configResolved(resolved) {
config = resolved
env = readEnv()
},
resolveId(id) {
if (id === 'virtual:auto-api') return apiId
if (id === 'virtual:env') return envId
},
async load(id) {
if (id === apiId) return generateAutoApiModule(path.resolve(config.root, apiDir), config.root)
if (id === envId) return generateEnvModule(env)
},
configureServer(server) {
const apiRoot = path.resolve(config.root, apiDir)
const envFiles = ['.env', '.env.local', '.env.' + config.mode, '.env.' + config.mode + '.local']
.map(file => path.resolve(config.envDir, file))
server.watcher.add([apiRoot, ...envFiles])
const refresh = file => {
const absolute = path.resolve(file)
const relative = path.relative(apiRoot, absolute)
const inApi = relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)
let id
if (envFiles.includes(absolute)) { env = readEnv(); id = envId }
else if (inApi && /\.[jt]s$/.test(absolute)) id = apiId
if (!id) return
const mod = server.moduleGraph.getModuleById(id)
if (mod) server.moduleGraph.invalidateModule(mod)
server.ws.send({ type: 'full-reload', path: '*' })
}
for (const event of ['add', 'change', 'unlink']) server.watcher.on(event, refresh)
server.watcher.once('close', () => {
for (const event of ['add', 'change', 'unlink']) server.watcher.off(event, refresh)
})
}
}
}🧩 2. 自动 API 导入模块(virtual:auto-api)
类似 unplugin-auto-import,需要扫描文件夹:
ts
async function generateAutoApiModule(apiDir, root) {
let entries
try {
entries = await fs.readdir(apiDir, { withFileTypes: true })
} catch (error) {
if (error.code === 'ENOENT') return 'export {}'
throw error
}
const owners = new Map()
const exportsList = []
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
if (!entry.isFile() || !/\.[jt]s$/.test(entry.name) || entry.name.endsWith('.d.ts')) continue
const filepath = path.join(apiDir, entry.name)
const code = await fs.readFile(filepath, 'utf8')
const ast = parse(code, { sourceType: 'module', plugins: ['typescript'] })
const names = ast.program.body
.filter(node => node.type === 'ExportNamedDeclaration' && node.declaration?.type === 'FunctionDeclaration'
&& !node.declaration.declare)
.map(node => node.declaration.id.name)
for (const name of names) {
if (owners.has(name)) throw new Error('Duplicate API export: ' + name)
owners.set(name, filepath)
}
if (names.length) {
const id = '/@fs/' + filepath.replace(/\\/g, '/')
exportsList.push('export { ' + names.join(', ') + ' } from ' + JSON.stringify(id))
}
}
return exportsList.join('\n') || 'export {}'
}📌 特性:
- 自动扫描 API 文件夹
- 生成 import 表达式
- 导出直接声明的具名函数(包括 async),忽略字符串、注释及其他导出形式
- API 文件新增、修改或删除后失效模块并刷新页面
🧩 3. 生成虚拟环境变量模块(virtual:env)
Vite 的 import.meta.env 是一个对象,我们把它变成模块导出:
ts
function generateEnvModule(env) {
const named = Object.entries(env)
.filter(([key]) => /^[A-Z_][A-Z0-9_]*$/.test(key))
.map(([key, value]) => 'export const ' + key + ' = ' + JSON.stringify(value) + ';')
return named.join('\n') + '\nexport default ' + JSON.stringify(env) + ';'
}效果:
ts
import { VITE_API_URL, MODE } from 'virtual:env'🧩 4. 与 Vite 内置 import.meta.env 的边界
不要用文本替换劫持内置变量;它会误改字符串和注释,还可能产生未声明的标识符。这里显式导入:
ts
import { MODE } from 'virtual:env'
console.log(MODE)但更推荐:
- 让用户手动
import { MODE } from 'virtual:env' - 或自动注入(更复杂:AST 注入,不在本示例中)
🔥 5. HMR 热更新逻辑
下面概括第 1 节监听器的处理顺序;片段省略外围作用域,不是独立插件。
① API 文件变化 → 更新 virtual:auto-api
ts
// API paths are checked relative to apiRoot.
// On add/change/unlink, invalidate apiId if it has been loaded.② .env 或 .env.* 变化 → 更新 virtual:env
ts
// Match the four env files for config.mode exactly.
// Read public env again, then invalidate envId if loaded.③ moduleGraph.invalidateModule
ts
const moduleNode = server.moduleGraph.getModuleById(id)
if (moduleNode) server.moduleGraph.invalidateModule(moduleNode)④ 发送整页刷新消息
ts
server.ws.send({ type: 'full-reload', path: '*' })这里选择整页刷新,不需要业务模块声明自接受热更新。
🧪 6. 最终完整效果
📌 使用自动 API:
ts
import { useUser, useFetch } from 'virtual:auto-api'📌 使用虚拟 env:
ts
import { VITE_APP_NAME, MODE } from 'virtual:env'📌 文件变化后自动刷新:
ts
// The configureServer watcher invalidates virtual modules,
// then sends a full-reload message to the client.