6. 模块联邦--@originjs/vite-plugin-federation

44 阅读1分钟

1.仓库官网

www.npmjs.com/package/@or…

1.配置页面+使用

    1. name 定义当前模块联邦的唯一标识名称,用于区分不同模块。在远程模块(Remote)中,该名称需与宿主(Host)配置的 remotes 字段中的键名对应。
    1. filename 指定远程模块的入口文件名,默认值为 remoteEntry.js。该文件会汇总所有暴露的组件和依赖,供宿主加载。
    1. exposes 定义远程模块对外暴露的组件或模块路径,宿主可通过这些路径动态加载资源。支持组件文件(如 .vue)和纯 JS 模块。
    1. remotes 在宿主模块中配置远程模块的入口地址,用于加载远程资源。需与远程模块的 name 和 filename 匹配。
    1. shared 定义共享的依赖库(如 Vue、React),确保宿主和远程模块使用同一依赖实例,避免重复加载。支持配置依赖版本。
    1. library 指定构建后的全局变量名,用于浏览器环境。在 UMD 格式下,可通过 window[libraryName] 访问模块。
    1. umd 控制是否生成 UMD 格式的构建文件,便于非模块化环境(如 CDN)使用
// vite.config.js
import federation from "@originjs/vite-plugin-federation";
export default {
    plugins: [
        federation({
            name: 'remote-app',
            filename: 'remoteEntry.js',
            // Modules to expose
            exposes: {
                './Button': './src/Button.vue',
            },
            remotes: {
                remote_app: "http://localhost:5001/assets/remoteEntry.js",
            },
            shared: ['vue']
        })
    ]
}

import { createApp, defineAsyncComponent } from "vue";
const app = createApp(Layout);
...
const RemoteButton = defineAsyncComponent(() => import("remote_app/Button"));
app.component("RemoteButton", RemoteButton);
app.mount("#root");