Single-SPA has emerged as a leading solution for implementing micro frontends, allowing development teams to build large-scale applications with greater autonomy and flexibility. In this article, we’ll explore Single-SPA in depth, provide practical implementation examples, and compare it with competing solutions.
What is Single-SPA?
Single-SPA (Single Single-Page Application) is a JavaScript framework for bringing together multiple JavaScript micro frontends in a frontend application. It provides the core infrastructure needed to:
- Register and load applications on-demand
- Orchestrate the lifecycle of each application
- Handle route-based activation
- Facilitate communication between applications
- Support multiple frameworks simultaneously (React, Angular, Vue, etc.)
How Single-SPA Works
At its core, Single-SPA operates on a simple principle: it coordinates the mounting and unmounting of independent applications based on routing rules. Each micro frontend follows a lifecycle with clear hooks:
- Bootstrap: Initial preparation
- Mount: Render the application to the DOM
- Unmount: Clean up when navigating away
- Unload: Release resources when no longer needed
Let’s see how this works in practice with a comprehensive example.
Setting Up Single-SPA From Scratch
Let’s walk through the process of setting up a new Single-SPA application:
- Create Root Config: First, install the Single-SPA CLI:
npm install --global single-spa-cli
Then create a new root config:single-spa create
- Register Applications: The root config (as shown in the example above) registers each application with:
- A unique name
- A loading function
- Activity rules (when to show it)
- DOM element mounting point
- Create Micro Frontends: For each micro frontend, create a separate application that exports the required lifecycle methods:
bootstrap
mount
unmount
- Configure Shared Dependencies: Use import maps or SystemJS to share common dependencies across applications.
Key Advantages of Single-SPA
- Framework Agnostic: Mix and match different frameworks (React, Vue, Angular) in the same application
- Independent Deployments: Deploy changes to one micro frontend without rebuilding others
- Lazy Loading: Load applications only when needed
- Minimal Boilerplate: Simple API with clear lifecycle hooks
- Routing Integration: Built-in support for route-based application activation
- Community and Ecosystem: Growing ecosystem with helpers for various frameworks
Challenges and Solutions
1. Shared Dependencies
Challenge: Duplicate libraries across micro frontends can bloat the application.
Solution: Use import maps or Module Federation to share common dependencies.
2. State Management
Challenge: Coordinating state across independent applications.
Solution: Use browser storage, custom events, or dedicated state management libraries.
Broadcast event from one micro frontend
window.dispatchEvent(new CustomEvent('cart:update', {
detail: { itemCount: 5 }
}));
// Listen in another micro frontend
window.addEventListener('cart:update', (event) => {
console.log('Cart updated:', event.detail);
});
3. Styling Conflicts
Challenge: CSS from one micro frontend affecting another.
Solution: Use CSS-in-JS, Shadow DOM, or CSS Modules for encapsulation.
Single-SPA Competitors and Alternatives
Let’s compare Single-SPA with its main competitors:
Micro Frontend Framework Comparison
Diagram
1. Module Federation (Webpack 5)
Strengths:
- Native integration with webpack build system
- Efficient code sharing with better tree shaking
- Runtime dependency resolution
- More granular sharing at the module level
Weaknesses:
- Tied to webpack ecosystem
- Steeper learning curve
- Less mature than Single-SPA
Example:
webpack.config.js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'products',
filename: 'remoteEntry.js',
exposes: {
'./ProductList': './src/ProductList',
},
shared: ['react', 'react-dom'],
}),
],
};
2. Qiankun
Built on top of Single-SPA, Qiankun provides additional features specially designed for Chinese applications.
Strengths:
- JavaScript sandbox for better isolation
- Built-in CSS isolation
- Simplified API compared to Single-SPA
- HTML entry (load from HTML)
Weaknesses:
- Primarily documented in Chinese
- Some features are opinionated
Example:
main.js
import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'reactApp',
entry: '//localhost:3000',
container: '#container',
activeRule: '/react',
},
]);
start();
3. Piral
A complete portal solution with unique package format called “pilets.”
Strengths:
- Comprehensive tooling ecosystem
- Extension system
- Standardized micro frontend package format
- Built-in state management
Weaknesses:
- More opinionated approach
- Steeper learning curve for full adoption
Example:
index.tsx
import * as React from 'react';
import { PiralProvider, createInstance } from 'piral';
import { layout } from './layout';
const instance = createInstance({
requestPilets: async () => {
const response = await fetch('https://feed.piral.io/api/v1/pilet/demo');
return await response.json();
},
layout,
});
export default () => (
<PiralProvider instance={instance} />
);
4. IFrame-Based Solutions
The simplest approach using standard HTML iframes.
Strengths:
- Strong isolation
- Works with any technology
- No build-time integration
Weaknesses:
- Limited communication options
- Poor performance
- URL and history management challenges
- Styling and responsiveness issues
5. Server-Side Composition (Tailor/Podium)
Composing fragments on the server before sending to the client.
Strengths:
- Better initial load performance
- SEO friendly
- Less client-side JavaScript
Weaknesses:
- More complex server infrastructure
- Less interactive between fragments
- Higher latency for user interactions
Real-World Use Cases
1. Large E-commerce Platforms
Single-SPA can divide an e-commerce site into:
- Product catalog (React)
- Shopping cart (Vue)
- Checkout (Angular)
- User account (React)
Each team can work independently and release on their own schedule.
2. Enterprise Dashboards
For complex dashboards with multiple data visualizations:
- Main layout and navigation (Vue)
- Sales charts (React with D3)
- User management (Angular)
- Settings (Svelte)
3. Progressive Migration
For migrating from legacy frameworks to modern ones:
- Keep existing jQuery app running
- Gradually add React components
- Eventually replace all legacy code
Best Practices for Single-SPA
- Clearly Define Boundaries: Each micro frontend should represent a business domain, not a technical component.
- Design a Robust Communication Strategy: Use custom events, shared storage, or a message bus for inter-application communication.
- Create a Shared Component Library: Develop a common design system for consistency.
- Implement CI/CD Pipelines: Automate testing and deployment for each micro frontend.
- Plan for Error Handling: Use error boundaries and fallback content.
- Optimize Performance: Minimize shared dependencies and use code splitting.
- Consider Server-Side Rendering: For SEO and initial load performance.
Conclusion
Single-SPA provides a powerful foundation for building micro frontend applications that can scale with your organization. While competitors like Module Federation offer different approaches, Single-SPA’s framework-agnostic nature and mature ecosystem make it an excellent choice for teams looking to break down their frontend monoliths.
The choice between Single-SPA and alternatives depends on your specific requirements:
- Use Single-SPA when you need framework flexibility and a mature ecosystem.
- Use Module Federation when deep webpack integration and granular code sharing are priorities.
- Use Qiankun when you need enhanced isolation features and are working in Chinese markets.
- Use Piral when you want a complete portal solution with standardized extension points.
As micro frontend architecture continues to evolve, Single-SPA remains a solid choice for teams seeking independence while maintaining a cohesive user experience.
At 7Shades Digital, we specialised in creating strategies that help businesses excel in the digital world. If you’re ready to take your website to the next level, contact us today!