- package.json (main,files,version)
- vite.config.ts (entry)
- npm login npm publish
1. Vite配置 (vite.config.js):javascript

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
build: {
lib: {
entry: './src/index.js',
name: 'MyComponentLibrary',
fileName: 'index',
formats: ['es', 'umd']
},
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue'
}
}
}
}
});
3. package.json配置:

{
"name": "my-component-library",
"version": "1.0.0",
"main": "dist/index.umd.js",
"module": "dist/index.es.js",
"files": [
"dist"
],
"scripts": {
"build": "vite build",
"publish": "npm publish"
}
}

按需导入
import { createApp } from 'vue';
import App from './App.vue';
import MyComponentLibrary from 'my-component-library';
const app = createApp(App);
app.use(MyComponentLibrary, {
components: ['Button']
});
app.mount('#app');
全局导入
import { createApp } from 'vue';
import App from './App.vue';
import MyComponentLibrary from 'my-component-library';
const app = createApp(App);
app.use(MyComponentLibrary);
app.mount('#app')
3. 插件实现
- 为了实现按需导入和全局导入的功能,你需要在你的组件库中提供一个插件,并根据用户的选择来注册组件。
import { Button, Input } from './components';
const MyComponentLibrary = {
install(app, options = {}) {
if (options.components) {
if (options.components.includes('Button')) {
app.component('MyButton', Button);
}
if (options.components.includes('Input')) {
app.component('MyInput', Input);
}
} else {
app.component('MyButton', Button);
app.component('MyInput', Input);
}
}
};
export default MyComponentLibrary;