第三方组件包(vue3)

189 阅读1分钟

创建组件包:

  1. 创建项目 cnpm create vite 项目名

  2. 修改main.js文件

     import HelloWorld from "./components/HelloWorld";//组件
     import ModelDialog from "./components/ModelDialog";
    
     export {
       HelloWorld,
       ModelDialog,
     };
    
  3. 修改vite.config.js

     import { defineConfig } from "vite";
     import vue from "@vitejs/plugin-vue";
     import path from "path";
    
     export default defineConfig({
       build: {
         //指定输出路径
         outDir: "vite-lib",
         //构建为库。entry 是必需的
         lib: {
           entry: path.resolve(__dirname, "./src/main.js"),
           name: "lib",
           fileName: (format) => `index.${format}.js` // 打包后的文件名
         },
         rollupOptions: {
           // 确保外部化处理那些你不想打包进库的依赖
           external: ["vue", "element-plus"],
           output: {
             // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
             globals: {
               vue: "Vue",
               "element-plus": "ElementPlus",
             }
           },
         },
       },
       plugins: [
         vue({
         })
       ],
       //解决process is not defined报错
       define: {
         "process.env": {},
       },
       //共享选项
       resolve: {
         alias: {
           "@": path.resolve(__dirname, "./src/"),
           "~": path.resolve(__dirname, "./src/"),
         },
         extensions: [".js", ".ts", ".json", ".vue"],
         dedupe: ["vue"],
       },
       css: {
         preprocessorOptions: {
           //导入sass预编译程序
           scss: {
             additionalData: `@use "@/assets/css/mixin.scss" as *;`,
           },
         },
       },
     });
    

项目中引用

  1. 将打包后的文件放入到项目的根目录

image.png

  1. 全局引用(也可以局部引用)

     import App from "./App.vue";
     import { createPinia } from "pinia";
     import * as viteComponents from "@/vite-lib/index";
    
     const pinia = createPinia();
     const app = createApp(App);
    
     let arr = Object.values(viteComponents);
     arr.forEach((item) => {
       app.component(item.name, item);
     });
    
     app.mount("#app");