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;
相关推荐
萧鼎31 分钟前
Python 高性能Web框架神器 FastAPI:自动生成API文、基于Pydant、异步请求处理全搞定
前端·python·fastapi
IT_陈寒1 小时前
Redis误用keys命令把生产环境搞崩了,血的教训
前端·人工智能·后端
计算机魔术师2 小时前
5000亿估值冲刺科创板,DeepSeek 为何急着上市?
前端
我血条子呢2 小时前
前端解析word方案
前端·word
kyriewen2 小时前
我用 AI 写完一个需求后才发现,最难的不是 prompt,而是验收
前端·程序员·ai编程
申行2 小时前
Vue 3 + DYMO Connect Framework 实战:从标签模板到打印服务的完整实现
前端
两只羊ovo2 小时前
Vue 3 + DeepSeek 流式输出实战:从“干等”到“打字机”体验
前端·vue.js
Yeyu2 小时前
车载多 App 同屏渲染(二):SurfaceControlViewHost 跨进程
前端
樊小肆2 小时前
离谱,每轮请求 25% 的 token,竟在重发模型想完就扔的内心独白
前端·人工智能·agent
小妖现世2 小时前
前端面试复习笔记:React 高频题 + JS 手写题
前端