Vite 库模式构建
使用 Vite library mode 打包组件库/工具库时的入口、external 与多格式输出要点。
#concept
#growing
#frontend
#javascript
[!info] related notes
- 所属:插件与 SSR MOC
- 相关:库打包与 d.ts · 生产构建
Vite 库模式构建
这个概念为什么出现
应用模式倾向打包依赖;组件库若同时打包宿主框架,可能增加体积并产生多个 React/Vue 实例,影响 Hook 或运行时协作。
[!abstract] 一句话理解
build.lib产出库入口包;peer 依赖通过external保持外置。
最小配置直觉
下面针对 Vite 8,库的 package.json 使用 "type": "module",入口导出需要发布的 API。外置列表按实际 peerDependencies 选择,不要求每个库同时依赖三者。
import { defineConfig } from 'vite'
import { fileURLToPath } from 'node:url'
export default defineConfig({
build: {
lib: {
entry: fileURLToPath(new URL('./src/index.ts', import.meta.url)),
name: 'InventoryUI',
formats: ['es', 'cjs'],
fileName: (format) => format === 'es' ? 'inventory-ui.js' : 'inventory-ui.cjs',
},
rolldownOptions: {
external: (id) => /^(react|react-dom|vue)(\/|$)/.test(id),
},
},
})
react/jsx-runtime 等子路径也要外置;只列 react 不代表所有子路径都匹配。旧 Vite 7 标准实现用 rollupOptions,在 Vite 8 中它是弃用兼容入口。
exports.import / exports.require 应分别指向 .js / .cjs 实际产物;在 type: module 包内把 CJS 也命名为 .js 会让 Node 按 ESM 解释。
实践清单
- peerDependencies 与 external 对齐
- 类型声明另策(tsc/dts 插件)
- 用真实宿主项目联调
- 注意 CSS 是否应单独导出
本节总结
库模式第一原则:不要替宿主打包它自己的框架。
自测题
- 为什么 React 组件库通常 external react?
参考答案
保证使用宿主的 React 实例,避免双 React 与体积膨胀。