Vue.js Micro Frontend

Micro frontends are an architectural style where independently deliverable frontend applications are composed into a larger application. This concept extends the principles of microservices to the frontend world, allowing teams to build, deploy, and scale their parts of the application independently. This chapter will explore the integration of micro frontends with Vue.js, covering everything from basic concepts to advanced implementation details.

What are Micro Frontends?

Micro frontends involve breaking up a frontend monolith into smaller, manageable pieces that can be developed, tested, and deployed independently. Each micro frontend is a self-contained module that represents a distinct feature or part of the application.

Benefits of Micro Frontends

  • Scalability: Teams can work on different parts of the application simultaneously without stepping on each other’s toes.
  • Flexibility: Different micro frontends can use different frameworks and technologies.
  • Maintainability: Smaller codebases are easier to manage and understand.
  • Independent Deployment: Micro frontends can be deployed independently, allowing for faster release cycles.

Micro Frontend Architecture

Monolith vs Micro Frontend

In a monolithic frontend, all features and components are part of a single codebase. This can lead to challenges in scaling and maintaining the application. In contrast, a micro frontend architecture splits the application into smaller, self-contained units that can be developed and deployed independently.

Key Principles of Micro Frontend Architecture

  • Independence: Each micro frontend should be independently deployable and testable.
  • Isolation: Micro frontends should be isolated to prevent conflicts, such as CSS or JavaScript scope collisions.
  • Communication: Micro frontends should have a well-defined way of communicating with each other.

Setting Up a Micro Frontend Project with Vue.js

Tools and Libraries

To set up a micro frontend architecture, we need tools that facilitate the creation, deployment, and orchestration of micro frontends. Some popular tools include:

  • single-spa: A framework for bringing together multiple JavaScript micro frontends.
  • Module Federation: A Webpack 5 feature for sharing modules between separate builds.
  • Qiankun: A micro frontend framework based on single-spa.

Creating the Container Application

The container application is the shell that hosts and orchestrates the micro frontends.

Example:

				
					npx create-single-spa --module-type root-config

				
			

root-config setup:

				
					import { registerApplication, start } from "single-spa";

registerApplication({
  name: "@my-org/navbar",
  app: () => System.import("@my-org/navbar"),
  activeWhen: ["/"]
});

registerApplication({
  name: "@my-org/home",
  app: () => System.import("@my-org/home"),
  activeWhen: ["/home"]
});

start();

				
			

Creating Micro Frontend Applications

Micro frontends can be created similarly to regular Vue.js applications, with additional configuration for integration with the container.

Example:

				
					npx create-single-spa --module-type app-parcel --framework vue --package-manager npm

				
			

Micro frontend entry file (main.js):

				
					import Vue from 'vue';
import singleSpaVue from 'single-spa-vue';
import App from './App.vue';

const vueLifecycles = singleSpaVue({
  Vue,
  appOptions: {
    render(h) {
      return h(App);
    },
  },
});

export const bootstrap = vueLifecycles.bootstrap;
export const mount = vueLifecycles.mount;
export const unmount = vueLifecycles.unmount;

				
			

Communication Between Micro Frontends

Using Props and Events

Micro frontends can pass data using props and emit events to communicate changes.

Example:

				
					
<child-component :data="parentData" @update="handleUpdate"></child-component>

				
			

Shared State Management

A shared state management solution like Vuex can be used, but it needs to be carefully managed to avoid tight coupling.

Example:

				
					import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    sharedData: {}
  },
  mutations: {
    updateData(state, payload) {
      state.sharedData = payload;
    }
  }
});

				
			

Custom Events and Pub/Sub Model

Using a Pub/Sub model can decouple micro frontends further.

Event Bus Example:

				
					import Vue from 'vue';
export const EventBus = new Vue();

				
			

Publishing an Event:

				
					EventBus.$emit('event-name', eventData);

				
			

Subscribing to an Event:

				
					EventBus.$on('event-name', (eventData) => {
  // Handle event
});

				
			

Routing in Micro Frontends

Single-SPA Routing

single-spa provides a way to configure routes for each micro frontend.

Example:

				
					registerApplication({
  name: "@my-org/settings",
  app: () => System.import("@my-org/settings"),
  activeWhen: ["/settings"]
});

				
			

Nested Routing

Micro frontends can have their own nested routes using Vue Router.

Example:

				
					import Vue from 'vue';
import Router from 'vue-router';
import SettingsHome from './components/SettingsHome.vue';
import SettingsProfile from './components/SettingsProfile.vue';

Vue.use(Router);

const router = new Router({
  routes: [
    { path: '/', component: SettingsHome },
    { path: '/profile', component: SettingsProfile }
  ]
});

export default router;

				
			

Handling Navigation

Handling navigation between micro frontends needs careful consideration to ensure a seamless user experience.

Example:

				
					import { navigateToUrl } from 'single-spa';

function handleNavigation(event) {
  navigateToUrl(event.target.href);
}

document.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', handleNavigation);
});

				
			

Deployment Strategies

Independent Deployment

Each micro frontend should be built and deployed independently, allowing teams to release updates without affecting others.

Example CI/CD Configuration:

				
					stages:
  - build
  - deploy

build:
  stage: build
  script:
    - npm install
    - npm run build

deploy:
  stage: deploy
  script:
    - deploy-to-cdn ./dist

				
			

Continuous Integration/Continuous Deployment (CI/CD)

Using CI/CD pipelines ensures that micro frontends are automatically tested and deployed.

Versioning and Backward Compatibility

Maintaining backward compatibility is crucial to ensure that updates to one micro frontend do not break the entire application.

Example Versioning:

				
					{
  "name": "@my-org/navbar",
  "version": "1.0.0"
}

				
			

Best Practices and Common Pitfalls

Ensuring Isolation

  • Use unique CSS namespaces or CSS-in-JS solutions to prevent style clashes.
  • Avoid global state and side effects.

Optimizing Performance

  • Lazy load micro frontends to improve initial load time.
  • Use a shared library to reduce duplication of dependencies.

Security Considerations

  • Validate and sanitize data passed between micro frontends.
  • Implement robust authentication and authorization mechanisms.

Micro frontends offer a scalable and flexible way to build large, complex applications by breaking them down into smaller, manageable pieces. By integrating Vue.js with micro frontend architecture, teams can leverage the benefits of both technologies to create performant and maintainable applications. This chapter has provided a comprehensive guide to setting up, managing, and deploying micro frontends using Vue.js, covering everything from basic setup to advanced communication and routing strategies. Happy coding !❤️

Table of Contents