vue3+ts+vite發布組件到npm
系統環境
- vue:3.2.6
- vite:2.5.4
- ts:4.3.2
創建項目
npm init vite@latest

模板選擇vue、vue-ts
編寫組件
打開項目 在src/components文件夾下新增文件,我這里叫TestPub.vue
編寫代碼如下
<template>
<button class="testButtonClass">我是測試要發布的按鈕組件</button>
</template>
<script setup lang="ts">
</script>
<style>
.testButtonClass{
background-color: green;
}
</style>
拿到當前項目里測試一下
//app.vue
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import TestPub from './components/TestPub.vue'
</script>
<template>
<test-pub></test-pub>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
運行項目

完美~
編寫導出文件
在src目錄下新增文件export.ts
編寫代碼如下:
import TestPub from './components/TestPub.vue';
export { TestPub }
使用vite構建
編輯vite.config.ts文件,新增build屬性,參考鏈接:https://cn.vitejs.dev/guide/build.html#library-mode
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/export.ts'),
name: 'TestPub',
fileName: (format) => `testpub.${format}.ts`
},
rollupOptions: {
// 確保外部化處理那些你不想打包進庫的依賴
external: ['vue'],
output: {
// 在 UMD 構建模式下為這些外部化的依賴提供一個全局變量
globals: {
vue: 'Vue'
}
}
}
}
})
編寫package.json文件
{
"name": "ylm-test-publish",
"version": "0.0.2",
"files": [
"dist"
],
"module": "./dist/testpub.es.ts",
"main": "./dist/testpub.umd.ts",
"exports": {
".": {
"import": "./dist/testpub.es.ts",
"require": "./dist/testpub.umd.ts"
},
"./dist/style.css": {
"import": "./dist/style.css",
"require": "./dist/style.css"
}
},
"keywords": [
"test"
],
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"serve": "vite preview"
},
"dependencies": {
"vue": "^3.2.6"
},
"devDependencies": {
"@vitejs/plugin-vue": "^1.6.1",
"@vue/compiler-sfc": "^3.2.6",
"typescript": "^4.3.2",
"vite": "^2.5.4",
"vue-tsc": "^0.2.2"
}
}
構建項目
npm run build
構建完成會在dist文件夾生成這些文件

發布到npm
注冊賬號過程略
發布:
npm publish
導入到新項目
npm i ylm-test-publish
<script setup lang="ts">
import { TestPub } from 'ylm-test-publish';
import 'ylm-test-publish/dist/style.css'
</script>
<template>
<test-pub></test-pub>
</template>

若是想通過cdn方式引用需要編寫install函數
import xxxComponent from './components/xxxComponent.vue';
const components = [xxxComponent];
// 注冊組件
const install = function (App, options) {
components.forEach((component) => {
App.component(component.name, component);
});
};
export { install, xxxComponent }
然后調用的頁面
<script src="./xxxComponent.umd.js"></script>
app.use(xxxComponent)
