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;
相关推荐
葡萄城技术团队2 小时前
1000 人协同压测的环境瓶颈排查:CPU 争用与 Wi\-Fi
前端
excel3 小时前
Marked 与 Markdown 有什么区别?该怎么选?
前端
Da Da 泓4 小时前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
zxcvb1535 小时前
远程查看本地文档:一条轻量 Web 文件服务的工程化链路
前端·远程查看文档
niucloud-admin5 小时前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
北岛贰6 小时前
啵啵音乐迎来全新升级!
前端
hkNaruto7 小时前
【AI】基于大模型的AI游戏地图生成、控制方案:AI Native Game Harness 迁移操作手册
前端·人工智能·游戏
IT_陈寒8 小时前
Java序列化踩坑记:对象循环引用让我加班两小时
前端·人工智能·后端
Acro8 小时前
快给macOS 上的Grok Bot换一套皮肤
前端
flash俊杰8 小时前
双引擎 OCR 编排:逐页判定、视觉优先、partial 语义与三层超时
前端