习惯用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>
拿到当前项目里测试一下
//app.vue
<template>
<div>
<test-btn></test-btn>
</div>
</template>
<script setup>
import TestBtn from './components/TestBtn.vue'
</script>
<style scoped>
</style>
src下新建index.js
//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.config.js文件,新增build属性,vite中文文档
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
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: {
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
vue: 'Vue'
}
}
}
}
})
{
"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官网
在dist文件生成package.json文件,自定义组件名(唯一,重名报错重新起一个就行),版本号每次上传要高于前一次版本号
//dist文件下
npm init -y
//package.json
{
"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 publish
npm i test-btn-ui
//main.js
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')
//页面.vue
<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包