Running an Angular and React Hybrid App Locally

Run Angular and React Hybrid App Locally | Step-by-Step Guide

In modern web development, enterprises often use multiple frontend frameworks due to legacy applications, team preferences, or specific technical requirements. Running an Angular and React hybrid application is a practical approach to leveraging the strengths of both frameworks in a single project. In this guide, we will explore how to set up Angular as a shell application while integrating React micro frontends using Web Components and optimizing performance with lazy loading.

Why Use a Hybrid Approach?

Before diving into implementation, let’s discuss the advantages of using both Angular and React in a single application:

  • Code Reusability: Organizations with existing React components can integrate them into Angular apps without rewriting them.
  • Gradual Migration: Legacy AngularJS or Angular apps can slowly transition to React without a full rewrite.
  • Team Flexibility: Different teams can work with their preferred framework while maintaining a cohesive application.
  • Micro Frontend Architecture: Allows independent development and deployment of different parts of the application.
  • Performance Optimization: With proper setup, micro frontends can be loaded on demand, reducing the initial load time.

Setting Up Angular as the Shell App

To begin, we will create an Angular application that serves as the shell, hosting the React micro frontends.

Step 1: Create a New Angular Application

Run the following command to create a new Angular project:

ng new angular-shell --style=scss --routing
cd angular-shell

Step 2: Configure Web Components in Angular

To integrate React components, we will use Angular’s support for Web Components.

  1. Install necessary dependencies:
ng add @angular/elements
npm install ngx-build-plus --save-dev
  1. Modify angular.json to support Web Components:
"builders": {
  "custom-webpack": {
    "builder": "ngx-build-plus:browser",
    "options": {
      "outputPath": "dist/angular-shell",
      "index": "src/index.html",
      "main": "src/main.ts",
      "polyfills": "src/polyfills.ts"
    }
  }
}
  1. Update main.ts to define Web Components:
import { createCustomElement } from '@angular/elements';
import { AppComponent } from './app/app.component';

const appElement = createCustomElement(AppComponent, { injector });
customElements.define('angular-shell', appElement);

Adding React Micro Frontends

Step 1: Create a React Micro Frontend

  1. Generate a new React application:
npx create-react-app react-mfe
cd react-mfe
  1. Install Web Components polyfill:
npm install @webcomponents/custom-elements --save
  1. Modify index.js to define the Web Component:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class ReactMicroFrontend extends HTMLElement {
  connectedCallback() {
    ReactDOM.render(<App />, this);
  }
}

customElements.define('react-micro-frontend', ReactMicroFrontend);

Step 2: Integrate React Micro Frontend into Angular

  1. Build the React app:
npm run build
  1. Copy the React build output to Angular’s assets folder.
  2. Use it in an Angular template:
<react-micro-frontend></react-micro-frontend>

Optimizing Performance with Lazy Loading

Lazy loading ensures that React micro frontends are loaded only when needed.

Step 1: Configure Lazy Loading in Angular

  1. Modify app-routing.module.ts:
const routes: Routes = [
  { path: 'react', loadChildren: () => import('./react-wrapper/react-wrapper.module').then(m => m.ReactWrapperModule) }
];

Step 2: Implement Lazy Loading for React

  1. Create a wrapper module for React components:
@NgModule({
  imports: [CommonModule],
  declarations: [ReactWrapperComponent],
  exports: [ReactWrapperComponent]
})
export class ReactWrapperModule {}

Advanced Performance Optimizations

In addition to lazy loading, other strategies can improve the efficiency of a hybrid Angular-React application:

Code Splitting

Both Angular and React support code splitting, which allows bundling different parts of the app separately. This helps improve initial loading performance.

  • Angular: Use Angular’s built-in lazy loading mechanism to load feature modules only when required.
  • React: Use React’s React.lazy and Suspense to load components dynamically.

Minification and Tree Shaking

Ensure that both Angular and React applications use minification and tree shaking to remove unused code:

ng build --prod
npm run build

Service Worker and PWA

Adding a service worker can enhance caching and performance for returning users. In Angular:

ng add @angular/pwa

For React, use Workbox for service worker integration.

Debugging a Hybrid Application

Debugging a hybrid application can be complex, but following best practices makes it easier:

  • Use Browser Developer Tools: Inspect Web Components using Chrome DevTools.
  • Enable Source Maps: Angular and React both support source maps for debugging.
  • Use Logging and Error Boundaries: Implement error boundaries in React to catch errors from micro frontends.

Security Considerations

Security is a key concern when integrating multiple frameworks. Some best practices include:

  • CORS Management: Ensure CORS policies allow seamless communication between different frontend parts.
  • Sanitizing User Input: Prevent XSS attacks by properly escaping and validating user inputs.
  • Secure Web Component Registration: Ensure only authorized scripts can register Web Components.

Conclusion

By combining Angular and React using Web Components, we enable a flexible and scalable hybrid architecture. Lazy loading and other performance optimizations ensure that components are loaded only when needed, reducing the initial load time. Debugging and security best practices help maintain a robust and maintainable application. This approach allows teams to collaborate efficiently while preserving existing investments in both frameworks, making it a powerful strategy for modern web applications.

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post