The user wants a guide or a demonstration of how to create a React application using a micro-frontend architecture with the single-spa framework.
1. Understanding the Goal:
The objective is to set up a micro-frontend system where:
There is a Root Config (Container/Host): The main HTML/JS file that orchestrates everything.
There are Micro-frontends (MFEs): Independent applications (in this case, React) loaded by the root config.
The tooling used is single-spa.
The framework for the MFEs is React.
2. Key Components of single-spa:
Root Config: Usually contains:
index.ejs (HTML template).
activity functions (determining which app loads when).
Registration of applications.
Utility Modules (optional but good practice): Shared logic/APIs.
Micro-frontends: The actual apps. In single-spa terminology, these need a specific lifecycle (bootstrap, mount, unmount). The single-spa-react helper makes this easy.
3. Tooling Strategy:
Historically, single-spa relied heavily on Webpack.
However, the modern standard for single-spa is to use Module Federation (via Webpack 5) or Vite (via vite-plugin-single-spa).
Decision: To keep it standard and robust, I should use the official create-single-spa generator, which sets up a Webpack-based environment. It handles the SystemJS/Webpack configuration complexity that usually trips people up.
Alternative: Using Vite is trendier, but create-single-spa is the "official" documented path for beginners. I will stick to the standard generator for stability, but maybe mention Module Federation. Actually, the generator now supports Module Federation or SystemJS. I'll stick to the classic SystemJS approach via the generator for simplicity, or a manual Webpack setup? No, the generator is best for a "Develop a React application..." prompt.
4. Step-by-Step Plan:
Prerequisites: Node.js.
Step 1: Create the Root Config (The Container).
Use npx create-single-spa.
Select "single-spa root config".
Step 2: Create the First MFE (React App 1).
Use npx create-single-spa.
Select "single-spa application / parcel".
Select "react".
Set organization name (important for naming conventions).
Step 3: Create the Second MFE (React App 2 - Optional but good for demo).
Repeat Step 2.
Step 4: Configuration (The Glue).
How to run them locally?
Port management (Root usually 9000, App 1 usually 8080, App 2 usually 8081).
Map imports in the Root Config's importmap (for local dev).
Modify root-config/src/root-config.ts to register the apps.
Step 6: Shared Dependencies.
React and ReactDOM should be shared to avoid multiple copies (performance/conflict issues). The create-single-spa generator handles this via importmap usually.
5. Refining the Guide (Self-Correction):
The create-single-spa generator creates a monorepo structure optionally, or separate folders. It's often easier to understand if we create separate folders for the Root and the Apps to simulate a real distributed environment.
Folder Structure:
root-config
app-navbar (React)
app-main (React)
6. Writing the Code/Explanation:
Intro: Explain what single-spa is (Router + Lifecycle manager).
Explain setPublicPath and the lifecycles exported.
Code snippet: src/main.tsx (or entry file) showing reactDomRender vs singleSpaReact.
Running Locally:
Need to run npm start in all terminals.
Connecting them:
Edit root-config/src/index.ejs (or equivalent) to point localhost ports.
Register the app in root-config.ts.
7. Formatting:
Use code blocks, clear headers, and comments explaining why we do things (e.g., single-spa: prefix in package names).
8. Crucial Detail - Webpack vs Vite:
The create-single-spa generator uses Webpack by default. Webpack configuration for micro-frontends (SystemJS) is notoriously tricky to set up manually. Using the generator is the only sane way to present a concise answer without writing 500 lines of webpack.config.js. I will proceed with the generator approach.
9. Draft of the Content:
Concept: Root Config + Micro-apps.
Prerequisites.
Step 1: Root Config. (Port 9000).
Step 2: App 1 (Navbar). (Port 8080).
Step 3: App 2 (Page). (Port 8081).
Step 4: Wiring it up. (The Import Map).
Step 5: Routing. (How to switch apps).
Self-Correction during drafting: Make sure to explicitly mention setting the "organization name". Usually, something like @my-org is used.
Let's verify the registration code.
registerApplication({ name: '@my-org/app1', app: () => System.import('@my-org/app1'), activeWhen: ['/'] });
This requires @my-org/app1 to be defined in the import map.
10. Final Polish:
Ensure the React code examples are modern (React 18+ syntax if possible, though single-spa helper sometimes hides the createRoot call, the standard single-spa-react helper handles it).
Let's write the response.
This guide demonstrates how to build a Micro-Frontend architecture using single-spa with React.
We will create three separate applications that run together in the browser:
Root Config (Container): The main HTML shell that orchestrates the apps.
Navbar (React): A micro-frontend that is always visible.
Main App (React): A micro-frontend that renders the home page content.
Prerequisites
Node.js installed.
Basic knowledge of React.
Step 1: Create the Project Structure
Create a main folder to hold all our projects (a "monorepo" style structure is easiest for local development).
bash
mkdir single-spa-demo
cd single-spa-demo
We will use the single-spa generator CLI to scaffold our projects efficiently.
bash
npm install -g create-single-spa
Step 2: Create the Root Config (The Container)
This is the "main" application. It doesn't usually have its own UI logic; instead, it loads the other apps and handles routing.
Run the generator:
bash
npx create-single-spa
Select options:
Module type:single-spa root config
Directory:root-config (Keep default)
Organization name:demo (Use this for consistency)
Project name:root-config (Keep default)
Package manager:npm (or yarn/pnpm)
Run the Root Config:
bash
cd root-config
npm install
npm start
This usually runs on Port 9000.
Open http://localhost:9000 in your browser. You should see a generic "Loading..." text or a placeholder.
Step 3: Create the Navbar Micro-Frontend
This will be a simple React component shared across the app.
Go back to the parent directory and run the generator:
bash
cd ..
npx create-single-spa
Select options:
Module type:single-spa application / parcel
Directory:navbar
Framework:react
Organization name:demo
Project name:navbar
Run the Navbar:
bash
cd navbar
npm install
npm start
This usually runs on Port 8080.
Modify src/main.tsx (or root.component.js):
Replace the generated component code with a simple Navbar layout.
Locate src/root-config.ts:
Register the applications.
javascript
// root-config/src/root-config.ts
import { registerApplication, start } from "single-spa";
import * as isActive from "./activity-functions";
// Register Navbar (Always active)
registerApplication({
name: "@demo/navbar",
app: () => System.import("@demo/navbar"),
activeWhen: "/",
});
// Register Main App (Active everywhere except specific exclusions if needed)
registerApplication({
name: "@demo/main-app",
app: () => System.import("@demo/main-app"),
activeWhen: isActive.prefix(location, "/"),
});
start();
Step 6: Shared Dependencies (React Import)
By default, single-spa generators bundle React inside every micro-app. In production, you want to load React only once to save bandwidth and ensure Context/Hooks work across boundaries.
In root-config/src/index.ejs:
Add React and ReactDOM as external modules in the import map.
In navbar and main-appwebpack.config.js (or similar):
Ensure React is marked as external so Webpack doesn't bundle it.
(The create-single-spa generator usually handles this if you select "Yes" to shared dependencies during setup, or you can manually add externals: ['react', 'react-dom'] in webpack config).
Step 7: Run and Test
Open 3 terminals.
Terminal 1: cd root-config -> npm start (Port 9000)
Terminal 2: cd navbar -> npm start (Port 8080)
Terminal 3: cd main-app -> npm start (Port 8081)
Visit:http://localhost:9000
You should see:
The Navbar (from the Navbar app) at the top.
The Content (from the Main App) below it.
If you edit code in the Navbar app and save, the browser will update without refreshing the Main App state.
Summary of Architecture
Root Config: Acts as the "Orchestrator". It decides what goes where based on the URL.
SystemJS: Handles loading the JavaScript modules dynamically in the browser.
Micro-frontends: Completely independent builds. You could theoretically rewrite the main-app in Vue.js next week, and as long as it exports the bootstrap, mount, and unmount lifecycles, the Root Config won't care.