Building Micro Frontends with React, Vue, and Single-spa

Building Micro Frontends with React, Vue, and Single-spa

In this tutorial I'll share what I've learned and show you how to build a micro-frontend app consisting of a React and a Vue application.

Originally published by Nader Dabit at https://dev.to

Over the past few weeks the there has been a ton of discussion around micro-frontends (some negative, some positive).

When I see something new and controversial like this, I always want to try it out myself to see what all of the hype is about and also so I can form my own opinions about the subject.

This lead me down the path to creating a micro-frontend application that rendered two separate React applications along with a single Vue application.

In this tutorial I'll share what I've learned and show you how to build a micro-frontend app consisting of a React and a Vue application.

To view the final code for this application, click here.
Single SPA

The tool we will be using to create our project is Single SPA - A javascript framework for front-end microservices.

Single SPA enables you to use multiple frameworks in a single-page application, allowing you to split code by functionality and have Angular, React, Vue.js, etc. apps all living together.

You may be used to the days of the Create React APP CLI and the Vue CLI. With these tools you can quickly spin up an entire project, complete with webpack configurations, dependencies, and boilerplate ready to go for you.

If you're used to this ease of setup, then this first part may be somewhat jarring. That is because we will be creating everything from scratch, including installing all of the dependencies we need as well as creating the webpack and babel configuration from scratch.

If you are still curious what Single SPA does or why you may want to build using a micro-frontend architecture, check out this video.
Getting Started

The first thing you'll need to do is create a new folder to hold the application and change into the directory:

mkdir single-spa-app 
cd single-spa-app 

Next, we'll initialize a new package.json file:

npm init -y 

Now, this is the fun part. We will install all of the dependencies that we will need for this project. I will split these up into separate steps.

Installing regular dependencies

npm install react react-dom single-spa single-spa-react single-spa-vue vue 

Installing babel dependencies

npm install @babel/core @babel/plugin-proposal-object-rest-spread @babel/plugin-syntax-dynamic-import @babel/preset-env @babel/preset-react babel-loader --save-dev 

Installing webpack dependencies

npm install webpack webpack-cli webpack-dev-server clean-webpack-plugin css-loader html-loader style-loader vue-loader vue-template-compiler --save-dev 

Now, all of the dependencies have been installed and we can create our folder structure.

The main code of our app will live in a src directory. This src directory will hold subfolders for each of our applications. Let's go ahead and create the react and vue application folders within the src folder:

mkdir src src/vue src/react 

Now, we can create the configuration for both webpack and babel.

Creating webpack configuration

In the root of the main application, create a webpack.config.js file with the following code:

const path = require('path');

const webpack = require('webpack');

const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const VueLoaderPlugin = require('vue-loader/lib/plugin')

 

module.exports = {

  mode: 'development',

  entry: {

    'single-spa.config': './single-spa.config.js',

  },

  output: {

    publicPath: '/dist/',

    filename: '[name].js',

    path: path.resolve(__dirname, 'dist'),

  },

  module: {

    rules: [

      {

        test: /.css$/,

        use: ['style-loader', 'css-loader']

      }, {

        test: /.js$/,

        exclude: [path.resolve(__dirname, 'node_modules')],

        loader: 'babel-loader',

      },

      {

        test: /.vue$/,

        loader: 'vue-loader'

      }

    ],

  },

  node: {

    fs: 'empty'

  },

  resolve: {

    alias: {

      vue: 'vue/dist/vue.js'

    },

    modules: [path.resolve(__dirname, 'node_modules')],

  },

  plugins: [

    new CleanWebpackPlugin(),

    new VueLoaderPlugin()

  ],

  devtool: 'source-map',

  externals: [],

  devServer: {

    historyApiFallback: true

  }

};

Creating babel configuration

In the root of the main application, create a .babelrc file with the following code:

{

  "presets": [

    ["@babel/preset-env", {

      "targets": {

        "browsers": ["last 2 versions"]

      }

    }],

    ["@babel/preset-react"]

  ],

  "plugins": [

    "@babel/plugin-syntax-dynamic-import",

    "@babel/plugin-proposal-object-rest-spread"

  ]

}

Initializing Single-spa

Registering applications is how we tell single-spa when and how to bootstrap, mount, and unmount an application.

In the webpack.config.js file we set the entry point to be single-spa.config.js.

Let's go ahead and create that file in the root of the project and configure it.

single-spa.config.js 

import { registerApplication, start } from 'single-spa'

 

registerApplication(

  'vue',

  () => import('./src/vue/vue.app.js'),

  () => location.pathname === "/react" ? false : true

);

 

registerApplication(

  'react',

  () => import('./src/react/main.app.js'),

  () => location.pathname === "/vue"  ? false : true

);

 

start();

 This file is where you register all of the applications that will be part of the main single page app. Each call to registerApplication registers a new application and takes three arguments:

  1. App name
  2. Loading function (what entrypoint to load)
  3. Activity function (logic to tell whether to load the app)

Next, we need to create the code for each of our apps.

React app

In src/react, create the following two files:

touch main.app.js root.component.js

src/react/main.app.js 

import React from 'react';

import ReactDOM from 'react-dom';

import singleSpaReact from 'single-spa-react';

import Home from './root.component.js';

 

function domElementGetter() {

  return document.getElementById("react")

}

 

const reactLifecycles = singleSpaReact({

  React,

  ReactDOM,

  rootComponent: Home,

  domElementGetter,

})

 

export const bootstrap = [

  reactLifecycles.bootstrap,

];

 

export const mount = [

  reactLifecycles.mount,

];

 

export const unmount = [

  reactLifecycles.unmount,

];

 src/react/root.component.js

import React from "react"
const App = () => <h1>Hello from React</h1>
export default App

Vue app

In src/vue, create the following two files:

touch vue.app.js main.vue

src/vue/vue.app.js 

import Vue from 'vue';

import singleSpaVue from 'single-spa-vue';

import Hello from './main.vue'

 

const vueLifecycles = singleSpaVue({

  Vue,

  appOptions: {

    el: '#vue',

    render: r => r(Hello)

  }

});

 

export const bootstrap = [

  vueLifecycles.bootstrap,

];

 

export const mount = [

  vueLifecycles.mount,

];

 

export const unmount = [

  vueLifecycles.unmount,

];

 src/vue/main.vue 

<template>

  <div>

      <h1>Hello from Vue</h1>

  </div>

</template>

 Next, create the index.html file in the root of the app:

touch index.html

index.html 

<html>

  <body>

    <div id="react"></div>

    <div id="vue"></div>

    <script src="/dist/single-spa.config.js"></script>

  </body>

</html>

Updating Package.json with scripts

To run the app, let's add the start script as well as a build script in package.json:

"scripts": {

  "start": "webpack-dev-server --open",

  "build": "webpack --config webpack.config.js -p"

}

Running the app

To run the app, run the start script:

npm start

Now, you can visit the following URLs:

# renders both apps

http://localhost:8080/

 

renders only react

http://localhost:8080/react

 

renders only vue

http://localhost:8080/vue

 To view the final code for this application, click here.
Conclusion

Overall, setting up this project was fairly painless with the exception of all of the initial boilerplate setup.

I think in the future it would be nice to have some sort of CLI that handles much of the boilerplate and initial project setup.

If you have the need for this type of architecture, Single-spa definitely seems like the most mature way to do it as of today and was really nice to work with.

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.

Develop this one fundamental skill if you want to become a successful developer

Throughout my career, a multitude of people have asked me&nbsp;<em>what does it take to become a successful developer?</em>

Throughout my career, a multitude of people have asked me what does it take to become a successful developer?

It’s a common question newbies and those looking to switch careers often ask — mostly because they see the potential paycheck. There is also a Hollywood level of coolness attached to working with computers nowadays. Being a programmer or developer is akin to being a doctor or lawyer. There is job security.

But a lot of people who try to enter the profession don’t make it. So what is it that separates those who make it and those who don’t? 

Read full article here

Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.