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;
相关推荐
tuokuac21 分钟前
nginx配置前端请求转发到指定的后端ip
前端·tcp/ip·nginx
程序员爱钓鱼25 分钟前
Go语言实战案例-开发一个Markdown转HTML工具
前端·后端·go
万少1 小时前
鸿蒙创新赛 HarmonyOS 6.0.0(20) 关键特性汇总
前端
还有多远.1 小时前
jsBridge接入流程
前端·javascript·vue.js·react.js
蝶恋舞者1 小时前
web 网页数据传输处理过程
前端
非凡ghost1 小时前
FxSound:提升音频体验,让音乐更动听
前端·学习·音视频·生活·软件需求
吃饭最爱2 小时前
html的基础知识
前端·html
我没想到原来他们都是一堆坏人2 小时前
(未完待续...)如何编写一个用于构建python web项目镜像的dockerfile文件
java·前端·python
前端Hardy2 小时前
HTML&CSS:有趣的漂流瓶
前端·javascript·css
前端Hardy2 小时前
HTML&CSS :惊艳 UI 必备!卡片堆叠动画
前端·javascript·css