Angular Host for React Microfrontends
Rany ElHousieny, PhD???
Generative AI ENGINEERING MANAGER | ex-Microsoft | AI Solutions Architect | Generative AI & NLP Expert | Proven Leader in AI-Driven Innovation | Former Microsoft Research & Azure AI | Software Engineering Manager
In this article, I will create an Angular host and consume your remote React button component.
Prerequisites
Step 1: Create a New Angular Project:
ng new angular-host
Step2: Install Dependencies:
cd angular-host
npm install @angular-architects/module-federation --save
npm install @angular-architects/module-federation-runtime --save
Step3: Create the Angular Component
Use the Angular CLI to generate a new component:
ng generate component button-wrapper
Inside the button-wrapper.component.ts, add the following:
// src/app/button-wrapper/button-wrapper.component.ts
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { loadRemoteModule } from '@angular-architects/module-federation';
import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
@Component({
selector: 'app-button-wrapper',
template: '<div #buttonContainer></div>',
styleUrls: ['./button-wrapper.component.css']
})
export class ButtonWrapperComponent implements AfterViewInit {
@ViewChild('buttonContainer', { static: true }) buttonContainer!: ElementRef;
async ngAfterViewInit() {
const ButtonModule = await loadRemoteModule({
remoteEntry: 'https://localhost:8080/remoteEntry.js',
remoteName: 'react_remote',
exposedModule: './Button'
});
const ReactButton = ButtonModule.default; // Assuming default export
const reactElement = React.createElement(ReactButton, { label: 'Click Me' });
const container = this.buttonContainer.nativeElement;
const root = ReactDOM.createRoot(container);
root.render(reactElement); // Render using 'createRoot'
}
}
领英推荐
Step4: Register the Wrapper Component:
Add the ReactButtonWrapperComponent to your Angular module declarations:
// src/app/app.module.ts
import { ButtonWrapperComponent } from './button-wrapper/button-wrapper.component';
@NgModule({
declarations: [
AppComponent,
ButtonWrapperComponent,
...
Step5: Add Module Federation:
ng add @angular-architects/module-federation
Step 6: Modify the generated webpack.config.js:
remotes: {
react_remote: 'react_remote@https://localhost:8080/remoteEntry.js',
},
Step 7: Use the Wrapper Component:
Finally, use the wrapper component in your Angular templates where you want to display the React button:
<!-- src/app/app.component.html -->
<app-button-wrapper></app-button-wrapper>
--
9 个月Thanks very much for the article. There is only one doubt, and how to do with the React dependencies? Installing in the Angular project? Creating types.d.ts?