npm组件库搭建

  • package.json (main,files,version)
  • vite.config.ts (entry)
  • npm login npm publish

1. Vite配置 (vite.config.js):javascript

js 复制代码
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配置:

js 复制代码
{
  "name": "my-component-library",
  "version": "1.0.0",
  "main": "dist/index.umd.js", // UMD格式的入口文件
  "module": "dist/index.es.js", // ES模块格式的入口文件
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "vite build",
    "publish": "npm publish"
  }
}

按需导入

js 复制代码
import { createApp } from 'vue';
import App from './App.vue';
import MyComponentLibrary from 'my-component-library';

const app = createApp(App);

// 按需导入组件
app.use(MyComponentLibrary, {
  components: ['Button'] // 只导入Button组件
});

app.mount('#app');

全局导入

js 复制代码
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. 插件实现

  • 为了实现按需导入和全局导入的功能,你需要在你的组件库中提供一个插件,并根据用户的选择来注册组件。
js 复制代码
   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;
相关推荐
小小小小宇10 分钟前
React Lanes(泳道)机制
前端
zhangxingchao13 分钟前
Jetpack Compose 之 Modifier(上)
前端
龙萌酱20 分钟前
力扣每日打卡17 49. 字母异位词分组 (中等)
前端·javascript·算法·leetcode
工呈士37 分钟前
HTML与Web性能优化
前端·html
秃了才能变得更强38 分钟前
React Native 原生模块集成Turbo Modules
前端
旺旺大力包1 小时前
【 React 】重点知识总结 && 快速上手指南
开发语言·前端·react.js
咪库咪库咪1 小时前
使用Fetch api发起请求
前端
东华帝君1 小时前
nuxt + nuxt ui + nuxt i18n
前端
鹿九巫1 小时前
【CSS】超详细!一篇文章带你学会CSS的层叠,优先级与继承
前端
天天码行空1 小时前
UnoCSS原子CSS引擎-前端CSS救星
前端