作者:廖哲皓(Howard Liao)|Frontend Lead(Principal Engineer)
我是廖哲皓,從事前端開發 14 年以上。帶團隊時常遇到一種情況:有的團隊寫 React,有的寫 Vue,大家各自做好的元件,卻很難放進同一個頁面裡一起用。
這篇分享我做的一個小型微前端示範:在 Vue 3 的主程式裡,同時載入 React 寫的圖表和 Vue 寫的表格。完整程式碼放在 GitHub:https://github.com/necpoctt/micro-frontend-demo
常見的做法有 Module Federation、single-spa、qiankun 等。這些方案功能完整,但設定和學習成本也比較高。如果需求只是「把幾個元件嵌進另一個框架的頁面」,Web Components 是更輕量的選擇。
專案分成三個部分:
兩個元件庫都用 Vite 的 library mode 打包成單一 JS 檔。主程式只要用 script 標籤載入,就能像一般 HTML 標籤一樣使用這些元件。
Vue 內建 defineCustomElement,幾行就能完成:
import { defineCustomElement } from 'vue';
import TableCe from './components/Table.ce.vue';
customElements.define('remote-vue-table', defineCustomElement(TableCe));
元件檔名用 .ce.vue 結尾,Vue 會把元件的樣式一起放進 Shadow DOM。
React 沒有內建這個功能,所以我寫了一個小工具函式:建立一個繼承 HTMLElement 的類別,在 Shadow DOM 裡用 createRoot 掛載 React 元件;屬性改變時,在 attributeChangedCallback 裡重新 render。
class Wrapper extends HTMLElement {
static get observedAttributes() { return attributes; }
constructor() {
super();
const mount = document.createElement('div');
this.attachShadow({ mode: 'open' }).appendChild(mount);
this.root = ReactDOM.createRoot(mount);
}
connectedCallback() { this.render(); }
attributeChangedCallback() { this.render(); }
}
同一個函式可以註冊多個 React 元件,例如 remote-electricity-chart 和 remote-pie-chart。
在 host-app 的 index.html 載入兩個打包好的檔案,接著就能在 Vue 範本裡直接使用:
<remote-vue-table
:table-data="JSON.stringify(tableData)"
@row-action="handleRowAction">
</remote-vue-table>
另外要在 vite.config.ts 裡設定 isCustomElement,告訴 Vue 編譯器 remote- 開頭的標籤是自訂元素,不要當成 Vue 元件解析。
適合:
不適合:
微前端不一定要很複雜。先從最小可行的方式開始,真的遇到規模問題再升級架構,通常是比較穩的做法。
關於我:廖哲皓(Howard Liao),台北 Frontend Lead(Principal Engineer),專長 React、Vue、Angular、TypeScript、Node.js。
個人網站:https://necpoctt.github.io/
GitHub:https://github.com/necpoctt
LinkedIn:https://www.linkedin.com/in/howard-liao-a2325aab/
本文同步發表於 Medium:https://medium.com/@necpoctt/d7c67d8f0766