整理不易,如果本文对你有帮助,欢迎点个【赞 👍】+【收藏 ⭐】+【关注 🧡】
📦Vue 组件库发布实战(含 TypeScript 支持)
在上一篇中我们完成了一个基础 Vue 3 组件的 npm 发布流程。本文将升级内容,带你完成一个支持 TypeScript 和多个组件的 Vue 组件库发布流程,适合想要长期维护 UI 库或工程化封装的你!
🔧一、项目初始化(TS + Vite)
① 创建目录并初始化项目
mkdir vue-ui-lib
cd vue-ui-lib
pnpm init -y
② 安装开发依赖
pnpm add vue@^3
pnpm add vite vue-tsc @vitejs/plugin-vue -D
pnpm add typescript -D
③ 初始化 TypeScript 配置
npx tsc --init
并编辑 tsconfig.json
:
{
"include": ["src"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Node",
"declaration": true,
"declarationDir": "dist/types",
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"jsx": "preserve",
"lib": ["ESNext", "DOM"]
}
}
📁二、组件结构设计(多组件支持)
推荐结构:
src/
components/
Button/
index.ts
Button.vue
Input/
index.ts
Input.vue
index.ts
示例组件:Button.vue
<template>
<button class="btn" @click="onClick">
<slot />
</button>
</template>
<script lang="ts" setup>
defineProps<{
onClick?: () => void
}>()
</script>
<style scoped>
.btn {
padding: 8px 16px;
background-color: #409eff;
color: white;
border-radius: 4px;
border: none;
cursor: pointer;
}
</style>
对应的 index.ts
import Button from './Button.vue'
export default Button
根入口 src/index.ts
export { default as MyButton } from './components/Button'
export { default as MyInput } from './components/Input'
// 添加更多组件时,继续扩展
🏗️三、配置 Vite 构建为组件库
创建 vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
plugins: [vue()],
build: {
lib: {
entry: path.resolve(__dirname, 'src/index.ts'),
name: 'MyUILib',
fileName: (format) => `my-ui-lib.${format}.js`,
formats: ['es', 'umd']
},
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue'
}
}
}
}
})
🧾四、配置 package.json
{
"name": "@your-username/vue-ui-lib",
"version": "1.0.0",
"main": "dist/my-ui-lib.umd.js",
"module": "dist/my-ui-lib.es.js",
"types": "dist/types/index.d.ts",
"files": ["dist"],
"peerDependencies": {
"vue": "^3.0.0"
},
"scripts": {
"build": "vite build && vue-tsc --declaration --emitDeclarationOnly --outDir dist/types",
"prepublishOnly": "pnpm run build"
}
}
🚀五、构建 & 发布组件库
① 构建产物
pnpm run build
- 生成
dist/*.js
(构建好的 JS) - 生成
dist/types
(类型声明)
② 登录并发布
pnpm login
pnpm publish
✅ 包发布成功后,即可被安装使用:
pnpm add @your-username/vue-ui-lib
🧪六、在项目中使用你的组件库
<template>
<MyButton @click="sayHi">Hello</MyButton>
</template>
<script setup lang="ts">
import { MyButton } from '@your-username/vue-ui-lib'
const sayHi = () => alert('Hi from UI lib!')
</script>
📦七、如何持续更新和扩展
场景 | 操作 |
---|---|
➕ 添加新组件 | 在 components/ 下新建文件夹,并导出 |
🔁 更新版本 | 修改 package.json 中的 version |
📦 重新发布 | pnpm run build && pnpm publish |
📚总结回顾
步骤 | 内容 |
---|---|
1️⃣ | 初始化 TS + Vite 项目 |
2️⃣ | 编写 Vue 3 组件结构,支持多组件 |
3️⃣ | 配置 Vite 构建和类型输出 |
4️⃣ | 设置 package.json ,准备发布 |
5️⃣ | 构建并发布到 npm |
6️⃣ | 在其他项目中测试使用 |
7️⃣ | 持续维护和扩展版本 |
👏 这样一个支持 TypeScript 的 Vue 组件库就发布完成啦!可以无限扩展和维护。