- 创建组件库项目:
# 使用vite创建一个新项目
npm init vite@latest my-vue-component-library -- --template vue-ts
# 进入项目目录
cd my-vue-component-library
# 安装依赖
npm install
编写组件:
在src
目录下创建你的组件文件,例如MyButton.vue
。
<template>
<button :class="`my-button-size-${size}`">{{ label }}</button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'MyButton',
props: {
label: String,
size: {
type: String,
default: 'medium'
}
}
});
</script>
<style scoped>
.my-button-size-small {
/* 小按钮样式 */
}
.my-button-size-medium {
/* 中等按钮样式 */
}
.my-button-size-large {
/* 大按钮样式 */
}
</style>
配置库的入口文件:
在src
目录下创建index.ts
文件,作为库的入口。
// src/index.ts
export { default as MyButton } from './MyButton.vue';
- 配置
vite.config.ts
:
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
lib: {
entry: './src/index.ts',
name: 'MyVueComponentLibrary',
fileName: (format) => `my-vue-component-library.${format}.js`,
},
rollupOptions: {
// 确保外部化处理依赖
external: ['vue'],
output: {
globals: {
vue: 'Vue'
}
}
}
}
});
- 添加
package.json
配置:
{
"name": "my-vue-component-library",
"version": "1.0.0",
"description": "My Vue 3 Component Library",
"main": "dist/my-vue-component-library.umd.js",
"module": "dist/my-vue-component-library.esm.js",
"unpkg": "dist/my-vue-component-library.global.js",
"files": [
"dist"
],
"scripts": {
"build": "vite build"
},
"peerDependencies": {
"vue": "^3.0.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/username/my-vue-component-library.git"
},
"author": "Your Name",
"license": "MIT",
"keywords": ["vue", "components", "library"],
"homepage": "https://github.com/username/my-vue-component-library#readme"
}
发布到NPM:
确保你有一个NPM账号,登录后发布:
npm publish
- 使用组件库:
npm install my-vue-component-library
然后在你的Vue项目中使用:
<script setup lang="ts">
import { MyButton