Use Single-spa to create a micro front end based on React and Vue

Use Single-spa to create a micro front end based on React and Vue

Front end pioneer

Use Single-spa to create a micro front end based on React and Vue

Single SPA


Single SPA is a javascript framework for front-end microservices.

It allows you to use multiple frameworks in a single page application, so that you can split the code by function and make Angular, React, and Vue.js programs run together.

You may be accustomed to the CLI of React and Vue. With these tools, you can quickly create a project and prepare webpack configuration, dependencies, and boilerplate code.

If you are used to this kind of operation, you may find the first half of this article a bit cumbersome. Because we are going to create everything from scratch, including all the dependencies required for installation and creating webpack and babel configurations from scratch.

Environment and configuration


First create a new directory under the terminal and enter it:


mkdir single-spa-app

cd single-spa-app

Next, initialize the package.json file:


npm init -y

Then install all dependencies required by the project. In order to let everyone know what is installed, I break them down into separate steps here.

Install dependencies

</> Install general dependencies


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

</>Install 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

</> Install 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

After all dependencies are installed, create a directory structure.

We put the project code in the src directory. Include subfolders for each program in the directory. Continue to create the react and vue program directories in the src directory:


mkdir src src/vue src/react

Configure webpack and babel below.

Environment configuration

</>Configure Webpack

In the root directory of the main program, create a webpack.config.js file and add the following content:


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
  }
};

</>Configure babel

Create a .babelrc file in the root directory and add the following content:


{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "browsers": ["last 2 versions"]
      }
    }],
    ["@babel/preset-react"]
  ],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-proposal-object-rest-spread"
  ]
}

</>Initialize Single-spa

This step is to register your application to tell single-spa when and how to find, load and uninstall programs.

In the webpack.config.js file, set the entry to single-spa.config.js.

Create this file in the root directory 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 used to register each part of the main single-page application development with different frameworks. Each call to registerApplication will register a new application, which accepts three parameters:

  1. Application name
  2. Function to load (entry point to load)
  3. The function used to activate (the logic used to tell whether to load the application)
    then needs to create code for each application.

React application


Create the following two files in the src/react directory:


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 application


Create the following two files in the src/vue directory:


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 directory of the program:


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>

Update Package.json with script

Add startup script and build script in package.json:


"scripts": {
  "start": "webpack-dev-server --open",
  "build": "webpack --config webpack.config.js -p"
}

Run the program


Execute the program by running start:


npm start

It can now be accessed through the following URL:


# 渲染基于所有框架的程序
http://localhost:8080/

# 只渲染 react
http://localhost:8080/react

# 之渲染 vue
http://localhost:8080/vue

to sum up


Except for the initial configuration, other tasks are easy. It would be better if Single-spa could add a CLI for handling template files and initial project settings in the future.

If you need a micro-frontend architecture, Single-spa is undoubtedly the most mature method.

Guess you like

Origin blog.51cto.com/15077562/2609646