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;
相关推荐
web小白成长日记7 小时前
企业级 Vue3 + Element Plus 主题定制架构:从“能用”到“好用”的进阶之路
前端·架构
APIshop7 小时前
Python 爬虫获取 item_get_web —— 淘宝商品 SKU、详情图、券后价全流程解析
前端·爬虫·python
风送雨7 小时前
FastMCP 2.0 服务端开发教学文档(下)
服务器·前端·网络·人工智能·python·ai
XTTX1107 小时前
Vue3+Cesium教程(36)--动态设置降雨效果
前端·javascript·vue.js
LYFlied8 小时前
WebGPU与浏览器边缘智能:开启去中心化AI新纪元
前端·人工智能·大模型·去中心化·区块链
Setsuna_F_Seiei9 小时前
2025 年度总结:人生重要阶段的一年
前端·程序员·年终总结
model20059 小时前
alibaba linux3 系统盘网站迁移数据盘
java·服务器·前端
han_10 小时前
从一道前端面试题,谈 JS 对象存储特点和运算符执行顺序
前端·javascript·面试
aPurpleBerry10 小时前
React 01 目录结构、tsx 语法
前端·react.js
jayaccc10 小时前
微前端架构实战全解析
前端·架构