创建项目
- “vue”: “^3.2.8”
- “vite”: “^2.5.2”
习惯用HB的直接用创建vue3项目即可 或
npm init vite@latest
创建组件
打开项目 在src/components文件夹下新增文件,我这里叫TestBtn.vue
<template>
<button>我是测试要发布的按钮组件</button>
</template>
<script>
export default{
name:'test-btn'
}
</script>
<script setup>
</script>
<style>
</style>
拿到当前项目里测试一下
<template>
<div>
<test-btn></test-btn>
</div>
</template>
<script setup>
import TestBtn from './components/TestBtn.vue'
</script>
<style scoped>
</style>
导出组件
src下新建index.js
import TestBtn from "./components/TestBtn.vue";
export { TestBtn }
const components = [TestBtn];
const install = function(App, options) {
components.forEach((component) => {
App.component(component.name,component);
});
};
export default { install }
使用vite构建
编辑vite.config.js文件,新增build属性,vite中文文档
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.js'),
name: 'TestBtn',
fileName: (format) => `test-btn.${format}.js`
},
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue'
}
}
}
}
})
修改package.json文件
{
"name": "test-btn-ui",
"version": "0.0.1",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"files": ["dist"],
"main": "./dist/test-btn.umd.js",
"module": "./dist/test-btn.es.js",
"exports": {
".": {
"import": "./dist/test-btn.es.js",
"require": "./dist/test-btn.umd.js"
}
},
"dependencies": {
"vue": "^3.2.8"
},
"devDependencies": {
"@vitejs/plugin-vue": "^1.6.0",
"@vue/compiler-sfc": "^3.2.6",
"vite": "^2.5.2"
}
}
打包
生成dist文件
npm run build
注册->登录npm
按提示注册就可以 npm官网
发布前准备
在dist文件生成package.json文件,自定义组件名(唯一,重名报错重新起一个就行),版本号每次上传要高于前一次版本号
npm init -y
{
"name": "test-btn-ui",
"version": "1.0.4",
"description": "",
"main": "test-btn.es.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
发布到npm
npm publish
其他项目引用
npm i test-btn-ui
import { createApp } from 'vue'
import App from './App.vue'
import TestBtnUI from 'test-btn-ui'
import 'test-btn-ui/style.css'
createApp(App).use(TestBtnUI).mount('#app')
<template>
<test-btn></test-btn>
</template>
<script setup>
</script>
<style scoped>
</style>
参考: vue文档 vite文档 用Vue3.2 + Vite2.7 从0快速打造一个UI组件库 vue3+ts+vite 发布vue组件到npm包
|