📌 什麼是 @originjs/vite-plugin-federation

這是一個專為 Vite 和 Rollup 設計的插件,讓 Vite 專案也能支援 Webpack 5 帶起的「模組聯邦(Module Federation)」技術。


⚙️ 核心設定解析:exposesshared

vite.config.js 中,這兩個屬性是模組聯邦的靈魂:

1. exposes (對外開放的商品型錄)

定義 Remote 專案要對外提供哪些模組。這是一種介面隔離的設計,隱藏真實路徑。

2. shared (共用底層基礎設施)

宣告共用依賴(如 vue, react, pinia),避免在 Host 端重複下載套件或產生多個實體衝突。


💻 基本實作範例 (Vue 3 為例)

Remote 端 (提供者)

⚠️ 注意: Vite 的 Remote 預設需要執行 build 產出實體檔案後才能提供服務。

// vite.config.js
import federation from '@originjs/vite-plugin-federation'

export default {
  plugins: [
    federation({
      name: 'remote_app',
      filename: 'remoteEntry.js', // 預設入口檔名
      exposes: { './Button': './src/components/Button.vue' },
      shared: ['vue']
    })
  ],
  build: { target: 'esnext' } // 必須設定 esnext 以支援 top-level await
}