- Các bước tạo app shell (root) trong cấu trúc MicroFrontend với dự án angular 18 được tạo trước khi thêm @angular-architects/native-federation.
- Tải
@angular/clibản 18.
npm install -g @angular/cli@18.0.0- Yêu cầu bản node.js thuộc chu kỳ LTS tối thiểu là
v18.13.0trở lên.
- Tạo dự án shell (hoặc root).
ng new shell- Chọn các options tạo dự án và đợi hoàn tất install các phụ thuộc.
- Cài đặt
@angular-architects/native-federation.
ng add @angular-architects/native-federation --save-dev- Sử dụng lệnh ng add để tự động thay đổi cấu hình file package.json, angular.json, main.ts và tự động tạo file federation.config.js.
- Tạo remote mfe1: Tạo remote test
- Tạo thư mục assets và thêm vào angular.json (nếu chưa có):
...
"builder": "@angular/build:application",
"options": {
"browser": "src/main.ts",
"polyfills": [
"zone.js",
"es-module-shims"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "public"
},
"src/assets" //Đường dẫn tới thư mục assets
],
"styles": [
"src/styles.scss"
]
}
...
- Thêm file
federation.manifest.jsonvào thư mục assets (không thêm vào assets cũng được, nếu không thêm thì trong angular.json thêm đường dẫn tới file này).
{
"mfe1": "http://localhost:3001/remoteEntry.json"
... //Các remote khác
}
- Cập nhật main.ts.
import { initFederation } from '@angular-architects/native-federation';
initFederation('/assets/federation.manifest.json') // Thêm đường dẫn tới file federation.manifest.json
.catch(err => console.error(err))
.then(_ => import('./bootstrap'))
.catch(err => console.error(err));- Sử dụng hàm
loadRemoteModuleđể tải module được expose từ các remote.
import { loadRemoteModule } from '@angular-architects/native-federation';
...
loadRemoteModule({
remoteName: 'mfe1', //Tên remote app
exposedModule: './Component', // Tên expose của component hoặc module.
}).then((m) => {
return m.App; // Ví dụ ./Component của mfe1 expose component có class là App
})
...npm start- Dự án tham khảo khác: remote-host.vercel.app.
- Remote host: github.
- Remote products: github.
- Remote cart: github.
- Remote shared-ui: github.