适用范围:面向 Vite 5/6、TypeScript 5 和 Node.js 20.19+ / 22 的发布教学示例。API 扫描支持具名函数、类、简单变量和显式导出别名;不处理 export *、解构导出与类型导出。插件包类型与业务虚拟模块类型需要分别声明。
支持开发(dev)与构建(build)解析虚拟模块;构建时由打包器决定 tree-shaking。本文提供插件类型声明(.d.ts)、打包脚本、Rollup 配置与发布说明。
目标产出
vite-plugin-auto-all(TypeScript 实现)- 支持:
virtual:auto-api+virtual:env(dev & build)- 在 build 阶段提供 ES 模块与具名导出,参与打包器的 tree-shaking
- 生成
.d.ts类型声明文件(rollup-plugin-dts)- 可直接
npm publish的 package.json + 发布流程说明
一、设计要点
- Tree-shaking 原则:具名导出利于静态分析;未使用导出能否移除,还取决于源模块副作用、打包配置与访问方式。默认导出整个对象不保证逐属性裁剪。
- 开发(dev)模式:通过
resolveId/load提供虚拟模块;监听变化后失效缓存并整页刷新。 - 构建(build)模式:插件同时参与构建钩子,输出具名重导出;被引用的 API 源文件仍可能含副作用,不能由生成模块替它保证。
- TypeScript 支持:代码用 TypeScript 编写,打包输出
dist/(ESM & CJS),并生成类型声明dist/index.d.ts。 - 无副作用:package.json
sideEffects: false,并让输出为 ES modules。
二、项目结构
vite-plugin-auto-all/
├─ src/
│ ├─ index.ts // 插件入口
│ ├─ virtualApi.ts // 生成 virtual:auto-api 内容逻辑
│ ├─ virtualEnv.ts // 生成 virtual:env 内容逻辑
│ └─ (Options is exported from index.ts)
├─ rollup.config.mjs
├─ tsconfig.json
├─ package.json
├─ README.md
└─ .npmignore三、核心源码(TypeScript)
把下面文件放到 src/ 中。
src/virtualEnv.ts
ts
import { loadEnv } from 'vite'
export function loadClientEnv(envDir: string, mode: string, prefix = 'VITE_') {
if (!prefix) throw new Error('envPrefix must not be empty')
return loadEnv(mode, envDir, prefix)
}
export function generateEnvModuleCode(
env: Record<string, string | boolean>,
extra: Record<string, string | boolean> = {}
) {
const merged = { ...env, ...extra }
const named = Object.entries(merged)
.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(merged) + ';\n'
}src/virtualApi.ts
ts
import fs from 'node:fs/promises'
import path from 'node:path'
import { parse } from '@babel/parser'
export type ExportsMap = Record<string, { id: string; names: string[] }>
export async function scanApiDir(root: string, apiDir: string) {
const files: string[] = []
async function walk(dir: string) {
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
const file = path.join(dir, entry.name)
if (entry.isDirectory()) await walk(file)
else if (/\.[jt]sx?$/.test(entry.name) && !entry.name.endsWith('.d.ts')) files.push(file)
}
}
try {
await walk(path.resolve(root, apiDir))
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
return { files: [], exports: {} as ExportsMap }
}
const exportsMap: ExportsMap = {}
for (const file of files.sort()) {
const ast = parse(await fs.readFile(file, 'utf8'), {
sourceType: 'module', plugins: ['typescript', 'jsx']
})
const names = new Set<string>()
for (const node of ast.program.body) {
if (node.type === 'ExportAllDeclaration') throw new Error('Unsupported export *: ' + file)
if (node.type !== 'ExportNamedDeclaration' || node.exportKind === 'type') continue
const declaration = node.declaration
if (declaration) {
if (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') {
if (!declaration.declare && declaration.id) names.add(declaration.id.name)
} else if (declaration.type === 'VariableDeclaration' && !declaration.declare) {
for (const item of declaration.declarations) {
if (item.id.type !== 'Identifier') throw new Error('Unsupported destructured export: ' + file)
names.add(item.id.name)
}
}
}
for (const item of node.specifiers) {
if (item.type === 'ExportSpecifier' && item.exportKind === 'type') continue
const exported = item.exported
const name = exported.type === 'Identifier' ? exported.name : exported.value
if (name === 'default') continue
if (!/^[$A-Z_a-z][\w$]*$/.test(name)) throw new Error('Unsupported export name: ' + name)
names.add(name)
}
}
if (names.size) {
const id = '/@fs/' + file.replace(/\\/g, '/')
exportsMap[id] = { id, names: [...names] }
}
}
return { files, exports: exportsMap }
}
export function generateAutoApiModuleCode(exportsMap: ExportsMap) {
const owners = new Set<string>()
const lines: string[] = []
for (const { id, names } of Object.values(exportsMap)) {
for (const name of names) {
if (owners.has(name)) throw new Error('Duplicate API export: ' + name)
owners.add(name)
}
lines.push('export { ' + names.join(', ') + ' } from ' + JSON.stringify(id) + ';')
}
return lines.join('\n') || 'export {}'
}src/index.ts (插件入口)
ts
import type { Plugin, ResolvedConfig } from 'vite'
import path from 'node:path'
import { loadClientEnv, generateEnvModuleCode } from './virtualEnv.js'
import { scanApiDir, generateAutoApiModuleCode } from './virtualApi.js'
export interface Options {
apiDir?: string
envPrefix?: string
}
const API_ID = '\0virtual:auto-api'
const ENV_ID = '\0virtual:env'
export default function autoAllPlugin(options: Options = {}): Plugin {
const apiDir = options.apiDir || 'src/composables'
const prefix = options.envPrefix ?? 'VITE_'
let config: ResolvedConfig
let env: Record<string, string | boolean> = {}
const readEnv = () => ({
...loadClientEnv(config.envDir, config.mode, prefix),
MODE: config.mode, DEV: !config.isProduction,
PROD: config.isProduction, BASE_URL: config.base
})
return {
name: 'vite-plugin-auto-all',
configResolved(resolved) { config = resolved; env = readEnv() },
resolveId(id) {
if (id === 'virtual:auto-api') return API_ID
if (id === 'virtual:env') return ENV_ID
},
async load(id) {
if (id === ENV_ID) return generateEnvModuleCode(env)
if (id === API_ID) {
const result = await scanApiDir(config.root, apiDir)
return generateAutoApiModuleCode(result.exports)
}
},
async buildStart() {
env = readEnv()
const result = await scanApiDir(config.root, apiDir)
generateAutoApiModuleCode(result.exports)
},
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: string) => {
const absolute = path.resolve(file)
const relative = path.relative(apiRoot, absolute)
const inApi = relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)
let id: string | undefined
if (envFiles.includes(absolute)) { env = readEnv(); id = ENV_ID }
else if (inApi && /\.[jt]sx?$/.test(absolute)) id = API_ID
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)
})
}
}
}说明:扫描使用 AST 并保留显式别名;重名导出会报错。类型导出被跳过,未实现的导出形式需另行扩展;不会吞掉语法或权限错误。
四、打包配置(Rollup)
rollup.config.mjs(以 ESM 写法):
mjs
import { readFileSync } from 'node:fs'
import dts from 'rollup-plugin-dts'
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
const packages = [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})]
const external = id => id.startsWith('node:') || packages.some(name => id === name || id.startsWith(name + '/'))
export default [
{
input: 'dist/index.js',
output: [
{ file: pkg.module, format: 'es', sourcemap: true },
{ file: pkg.main, format: 'cjs', sourcemap: true, exports: 'named' }
],
external
},
{
input: 'dist/types/index.d.ts',
output: [{ file: pkg.types, format: 'es' }],
external,
plugins: [dts()]
}
]说明:先运行
tsc输出 JS 与dist/types/index.d.ts,再让 Rollup 分别打包;入口路径与下面的rootDir一致。
五、tsconfig.json
json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler",
"rootDir": "src",
"declaration": true,
"declarationDir": "dist/types",
"outDir": "dist",
"noEmitOnError": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}六、package.json
json
{
"name": "vite-plugin-auto-all",
"version": "1.0.0",
"description": "Vite virtual API and public env modules",
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.esm.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.esm.js",
"require": "./dist/index.cjs"
}
},
"files": ["dist"],
"sideEffects": false,
"scripts": {
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
"build:ts": "tsc -p tsconfig.json",
"build:rollup": "rollup -c",
"build": "npm run clean && npm run build:ts && npm run build:rollup",
"prepare": "npm run build"
},
"keywords": ["vite", "plugin", "virtual", "env"],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.26.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"rollup": "^3.0.0",
"rollup-plugin-dts": "^5.0.0",
"typescript": "^5.9.0",
"vite": "^5.4.21"
},
"peerDependencies": {
"vite": "^5.4.0 || ^6.0.0"
}
}七、发布前的关键注意事项(让 tree-shaking 生效)
- 模块导出形式:优先使用具名导出。生成层只重导出,源 API 模块的顶层副作用仍会影响裁剪,默认对象的属性裁剪不能一概保证。
- package.json
sideEffects: false:告诉打包器模块无副作用,从而允许摇树。 - 生成 ESM 输出:
module字段指向 ES 模块dist/index.esm.js,Rollup/webpack 能够更好执行 tree-shaking。 - 保证构建阶段虚拟模块可访问:插件不限制为 serve;
resolveId/load因此同时参与 dev 与 build,buildStart负责提前校验扫描结果。
八、使用范例
在目标项目中安装:
bash
npm i -D vite-plugin-auto-allvite.config.ts:
ts
import { defineConfig } from 'vite'
import autoAll from 'vite-plugin-auto-all'
export default defineConfig({
plugins: [ autoAll({ apiDir: 'src/composables' }) ]
})使用:
ts
// 可以直接从虚拟模块导入
import { useUser } from 'virtual:auto-api'
import { VITE_API_URL } from 'virtual:env'
// 也可 default import env
import env from 'virtual:env'未使用的具名导出通常可以移除,但仍需检查源模块副作用与实际构建结果。
九、生成类型(.d.ts)建议
- 插件选项类型已经从
src/index.ts导出;它不自动生成业务虚拟模块的导出类型。 - 在使用方项目创建
src/virtual-modules.d.ts,按实际业务声明导出;不要手改打包生成的dist/index.d.ts:
ts
// Consumer-side ambient declarations; this file has no top-level import/export.
declare module 'virtual:env' {
const env: Record<string, string | boolean>
export default env
export const MODE: string
export const DEV: boolean
export const PROD: boolean
export const BASE_URL: string
export const VITE_API_URL: string
}
declare module 'virtual:auto-api' {
export const useUser: typeof import('./composables/useUser').useUser
}rollup-plugin-dts可以帮助把.d.ts合并到dist/index.d.ts。
十、发布流程(检查清单 + 命令)
- 更新
package.json(name/version/author/license)。确保唯一包名。 npm run build(或 CI 自动化)- 登录 npm:
npm login - 发布:
npm publish --access public(若是 scoped 包,使用--access public) - Tag 和 Release(可选):
git tag v1.0.0 && git push --tags
CI 示例(GitHub Actions):推送匹配 v* 的标签时发布;请提交 lockfile 供 npm ci 使用。
十一、如何本地验证 tree-shaking 有效
- 在一个测试项目中安装本地包(
npm pack或yarn add ../path/to/your/plugin)。 - 在测试项目里
import { unusedFunc } from 'virtual:auto-api'不要在代码中引用,构建npm run build。 - 查看打包后的产物(例如
dist/assets/*.js),确认unusedFunc没出现在最终 bundle(或使用 source-map 分析)。 - 同时增加一个含顶层日志的 API 源文件,确认测试能识别副作用仍被保留;不要依靠插件包的
sideEffects: false消除业务源文件副作用。
十二、后续增强建议(你可以选择实现)
- 扩展 AST 扫描,支持
export *、解构导出与更完整的 TypeScript 语法。 - 支持
auto import按需按使用位置生成 import 语句(更接近 unplugin-auto-import)。 - 为
virtual:env生成env.d.ts并支持import.meta.env替换(AST + magic-string),使import.meta.env.FOO在 TS 中可被类型检查与自动完成。 - 提供
preset(例如 Vue preset、React preset)内置的常用 API 列表。 - 在 build 阶段把虚拟模块显式 emit 为 chunk(
this.emitFile({ type: 'chunk', id: virtualId }))以便做更精细 rollup 控制(optional)。
GitHub Actions自动发布到npm
你只需要把它放到:
.github/workflows/publish.yml✅ GitHub Actions:自动 build + 自动发布 npm + 自动创建 Release
yaml
name: Publish to npm
on:
push:
tags:
- "v*" # 例如 v1.0.0 时触发
permissions:
contents: write
jobs:
build-and-publish:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
registry-url: "https://registry.npmjs.org"
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test --if-present
- name: Build plugin
run: npm run build
# ---- 发布到 npm ----
- name: Publish to npm
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# ---- 自动创建 GitHub Release ----
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: |
dist/**🔐 需要你在 GitHub 设置的 Secrets
进入仓库 → Settings → Secrets → Actions → New repository secret
| Secret 名称 | 值 |
|---|---|
NPM_TOKEN | npm 的 publish token(npmjs.com → Access Tokens → Generate Fine-grained Token) |
📌 工作流触发方式
每次你 push 一个 tag:
git tag v1.0.0
git push origin v1.0.0GitHub Actions 会自动:
- 安装 Node 环境
npm ci装依赖- 跑测试
npm run build- 用
npm publish发布到 npm - 创建 GitHub Release,并附带
dist/**文件
🔧 如果你还希望支持 Beta / Alpha 发布
例如:
v1.1.0-beta.1那就保持同样的 tag 规则即可,npm 会按版本发布。