Scaling Frontend Development with Microfrontends: A Guide Using Vue 3, Vite, and Single-SPA
Microfrontends are revolutionizing how we build and scale large web applications. Instead of a monolithic frontend codebase, microfrontends allow you to break down your application into smaller, independent, and manageable units. This approach mirrors the benefits of microservices, bringing agility and scalability to the frontend development process. This guide explores the fundamentals of creating microfrontend applications using Vue 3, Vite, and Single-SPA.
What are Microfrontends?
Microfrontends represent an architectural style where independently deployable frontend applications are composed into a larger whole. Think of a website or web application as a collection of features, each owned and developed by a separate team. Each team is typically cross-functional, managing every aspect of their feature, from the database to the user interface.
Key Benefits of Microfrontends
- Improved Scalability: Multiple teams can work concurrently on different parts of the application without the constraints and potential conflicts of a single, large codebase.
- Technology Flexibility: Each microfrontend can be built using the technology stack best suited for its specific requirements. You’re not locked into a single framework or library for the entire application.
- Enhanced Resilience: If one microfrontend encounters an issue or needs to be taken offline, it doesn’t necessarily impact the functionality of the other microfrontends. This isolates failures and improves the overall robustness of the application.
- Independent Deployments: Each microfrontend team has freedom to deploy updates.
- Easier Maintenance: It allows for easier maintenance.
Introduction to Single-SPA: The Microfrontend Orchestrator
Single-SPA is a JavaScript framework that acts as a top-level router for microfrontends. It allows you to bring together multiple frontend applications, potentially built with different frameworks (like Vue, React, Angular, etc.), into a single cohesive user experience. Single-SPA manages the lifecycle of each microfrontend, dynamically loading and unloading them based on routing or other defined conditions.
Key Components of Single-SPA
- Root Configuration: This is the core of your Single-SPA setup. The root configuration is responsible for:
- Rendering the main HTML page.
- Registering each microfrontend application. This registration includes:
- A unique name for the microfrontend.
- A function that tells Single-SPA how to load the microfrontend’s code (typically an asynchronous import).
- An activity function (often based on the URL) that determines when the microfrontend should be active and mounted.
- Applications (Microfrontends): These are the individual microfrontend applications. Each application is essentially a Single Page Application (SPA) packaged as a module. Importantly, each microfrontend must implement specific lifecycle functions:
- bootstrap: Called once, before the microfrontend is mounted for the first time. Used for initial setup.
- mount: Called whenever the microfrontend needs to be displayed. This is where the microfrontend renders its content into the DOM.
- unmount: Called when the microfrontend needs to be removed from the DOM. This is where you should perform cleanup, like removing event listeners.
How Single-SPA Works (Simplified)
- The user navigates to a specific URL.
- Single-SPA’s root configuration checks the registered applications and their activity functions.
- If the URL matches the activity function of a registered microfrontend, Single-SPA calls that microfrontend’s
bootstrap
function (if it hasn’t been called before) and then itsmount
function. - The microfrontend renders its content.
- When the user navigates to a different URL, Single-SPA might call the
unmount
function of the previously active microfrontend and themount
function of the newly active one.
Building a Microfrontend Example with Vue 3 and Vite
This section outlines the conceptual steps involved in creating a microfrontend application using Vue 3, Vite, and Single-SPA.
Prerequisites
- Node.js and npm (or yarn) installed.
- Basic understanding of Vue 3 and its component structure.
- Familiarity with module bundlers like Vite.
Step 1: Creating the Root Application (Orchestrator)
The root application serves as the entry point and orchestrator for your microfrontends. Although using a framework is optional, for this context, we’ll use Vue 3.
- Create a new Vue 3 project: You can use the Vue CLI or Vite to scaffold a new project. Choose options like TypeScript support and Vue Router for a more robust setup.
- Install Single-SPA: Install the
single-spa
andsingle-spa-vue
packages. - Configure Vite (vite.config.ts): Use the
vite-plugin-single-spa
to configure your root application. This plugin simplifies the integration with Single-SPA. Set thetype
option to'root'
. - Create
single-spa.setup.ts
: file to import theregisterApplication
and thestart
function fromsingle-spa
.
Step 2: Creating a Microfrontend Application
- Create a new Vue 3 project: Create a new Vue 3 project, similar to how you created the root application. This will be your microfrontend.
- Install Dependencies: Install
single-spa-vue
andvite-plugin-single-spa
in your microfrontend project. - Configure Vite (vite.config.ts): Use the
vite-plugin-single-spa
plugin, but this time, set thetype
option to'mife'
(or a similar identifier) to indicate that this is a microfrontend. Also, configure a specificserverPort
for the development server (e.g., 4101) to avoid conflicts with the root application. - Modify
main.ts
: This is crucial. Instead of mounting the Vue application directly, you need to export the Single-SPA lifecycle functions (bootstrap
,mount
,unmount
). Thesingle-spa-vue
package provides a helper function to create these lifecycle functions from your Vue application instance.- Important: Only mount the Vue application directly (e.g.,
app.mount('#app')
) when running in development mode outside of the Single-SPA context. You can use an environment variable check (e.g.,import.meta.env.MODE === 'development'
) to conditionally mount the application.
- Important: Only mount the Vue application directly (e.g.,
Step 3: Handling Different Bundle Locations (Import Maps)
During development, your microfrontend’s entry point (e.g., main.ts
) might be served from a different URL than when it’s built for production. To handle this, use import maps.
- Create two import map files: In your root application, create
importMap.dev.json
(for development) andimportMap.json
(for production). - Define the mappings: In each file, define an import map that maps a consistent module name (e.g.,
@your-org/your-microfrontend
) to the correct URL for that environment. For example, inimportMap.dev.json
, it might point tohttp://localhost:4101/src/main.ts`, while in
importMap.json, it might point to
http://localhost:4101/assets/main.ts`. - Add
<script type="systemjs-importmap" src="./src/importMap.dev.js"></script>
in the index.html
Step 4: Registering the Microfrontend in the Root Application
- In
single-spa.setup.ts
(in the root application): Use theregisterApplication
function from Single-SPA to register your microfrontend.- name: A unique name for your microfrontend (e.g., “my-microfrontend”).
- app: An asynchronous function that imports your microfrontend using the module name you defined in the import map (e.g.,
() => import('@your-org/your-microfrontend')
). Use/* @vite-ignore */
to prevent Vite from trying to pre-bundle this dynamic import. - activeWhen: A function or a string that defines when the microfrontend should be active. This is often based on the URL path (e.g.,
'/my-microfrontend'
).
- Call
start()
: After registering all your microfrontends, call thestart()
function from Single-SPA to initialize the system.
Step 5: Routing and Teleportation (Addressing Common Issues)
- Problem: If both the root application and the microfrontend use Vue Router, you might end up with two Vue instances and routing conflicts. The microfrontend’s content might also be appended to the
body
instead of being rendered within the root application’s layout. -
Solution: Vue’s Teleport: Use Vue’s
<Teleport>
component within your microfrontend to render its content into a specific element within the root application’s DOM.- In the microfrontend (App.vue): Wrap the content you want to render within a
<Teleport>
component, targeting a specific element in the root application using a CSS selector (e.g.,to=".container"
). - In the root application: Make sure there’s an element with the corresponding selector (e.g.,
<div class="container"></div>
) where the microfrontend’s content should be injected. You might place this within your root application’s layout component. - Disable Teleport in development: to be able to see your component.
- In the microfrontend (App.vue): Wrap the content you want to render within a
- Routing within the Microfrontend: To enable internal routing within your microfrontend, configure its routes to be nested under the base path that Single-SPA uses to activate the microfrontend. For example, if your microfrontend is active at
/my-microfrontend
, define its internal routes as/my-microfrontend/foo
,/my-microfrontend/bar
, etc.
Conclusion
Microfrontends offer a powerful way to scale frontend development, enabling independent teams, technology flexibility, and improved resilience. While the initial setup can seem complex, understanding the core concepts of Single-SPA and leveraging tools like Vite and Vue’s Teleport can help you overcome common challenges and build robust, scalable web applications.
Innovative Software Technology: Your Partner in Microfrontend Development
Are you looking to leverage the power of microfrontends to scale your web application and empower your development teams? At Innovative Software Technology, we specialize in building modern, scalable, and maintainable web applications using cutting-edge technologies like Vue 3, Vite, and Single-SPA. Our expertise in microfrontend architecture ensures that your application benefits from:
- Faster Time to Market: Independent deployments and parallel development accelerate feature releases. Search engine optimization is crucial, and faster websites rank higher.
- Improved User Experience: Isolated microfrontends lead to a more responsive and resilient application, enhancing user satisfaction. Better user experience leads to higher engagement and conversion rates, both important SEO factors.
- Scalable Development Teams: Our solutions enable your teams to work autonomously, fostering innovation and productivity. A well-structured, maintainable codebase is easier for search engines to crawl and index.
- SEO Optimized Architecture: By utilizing server-side rendering (SSR) capabilities within individual microfrontends and ensuring clean, semantic HTML, we optimize your application for search engine crawlers, improving your organic visibility. We also focus on core web vitals and performance optimization, crucial for modern SEO.
Contact Innovative Software Technology today to discuss how we can help you implement a successful microfrontend strategy tailored to your specific needs and goals. We’ll help you build a future-proof web application that is both powerful and performant.