项目问题: 工作中有两个vue项目中有六个相同业务的页面,为了降低代码维护成本,遂提出了建立组件库以便后续维护一份代码,但两个项目vue大版本不同,一个是2.0版本,另一个是新的3.0版本,隧又提出在vue2.0项目基础上新建一个3.0版本的项目,用于载入vue3.0组件库逻辑。 于是:本篇仅记录vite3.0+vue3.0版本基础上如何生成组件库。
vite项目构建:
yarn create vite my-app-name
所有的组件都在 src/components/ 下,而组件汇集在src/components/index.ts中
export { default as VButton } from './VButton.vue';
export { default as VTable } from './VTable.vue';
// Other components you plan to publish go here
项目结构如下:
README.md
# Vue 3 + TypeScript + Vite构建组件库项目
## 开发环境启动
`
yarn dev
或者
npm run dev
`
## 生产构建
`
yarn build
或者
npm run build
`
## 工具说明
- @types/node(Node.js的type定义集合)
- vue-tsc (vue类型检查和dts构建命令行工具)
该组件库demo在github地址:git@github.com:MiyaTang07/vite-component-lib.git 且已发布npm包,包名即:vite-component-lib
package.json
{
"name": "vite-component-lib",
"files": ["dist"],
"main": "./dist/my-com.umd.js",
"module": "./dist/my-com.es.js",
"browser": "./dist/my-com.umd.js",
"repository": {
"type": "git",
"url": "git@github.com:MiyaTang07/vite-component-lib.git"
},
"exports": {
".": {
"import": "./dist/my-com.es.js",
"require": "./dist/my-com.umd.js"
}
},
"version": "0.0.1",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.2.37"
},
"devDependencies": {
"@types/node": "^18.7.19",
"@vitejs/plugin-vue": "^3.1.0",
"typescript": "^4.6.4",
"vite": "^3.1.0",
"vue-tsc": "^0.40.4"
}
}
而项目构建配置项如下:
vite.config.ts
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/components/index.ts'),
name: 'MyCom',
fileName: (format) => `my-com.${format}.js`,
},
rollupOptions: {
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// Add external deps here
globals: {
vue: 'Vue',
},
},
},
},
plugins: [vue()]
})
npm发布流程:
npm login
Username: // 输入注册时候的用户名
Password: // 密码
Email: (this IS public) // 邮箱code验证
npm publish
npm unpublish packageName // 即可将 npm 上的包删除
构建出来的产物如下:
发布成功后,就可以愉快地在项目中下载使用了,祝你今天快乐😊