search
HomeWeb Front-endVue.jsCreate a micro frontend using React, Vue and Single SPA
Create a micro frontend using React, Vue and Single SPAOct 28, 2020 pm 05:30 PM
javascriptreact.jsvue.jsfront endmicro frontend

This article will introduce you to how to create a micro front end using React, Vue and Single SPA. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Create a micro frontend using React, Vue and Single SPA

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 enable Angular, React, and Vue.js programs to run together.

You may be used to the CLI of React and Vue. These tools can quickly create projects and prepare webpack configuration, dependencies, boilerplate code, etc.

If you are used to this kind of operation, you may find the first half of this article a bit tedious. Because we are creating everything from scratch, including installing all required dependencies 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 for your project. In order to make it clear to everyone what is installed, I have broken them down into separate steps here.

Install dependencies

Install regular 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 the directory structure.

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

mkdir src src/vue src/react

Configure webpack and babel below.

Environment Configuration

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

Configuration babel

Create the .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 , used to tell single-spa the timing and method to find, load and uninstall the program.

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 developed for the main single-page application using different frameworks. Each time registerApplication is called, a new application is registered, which accepts three parameters:

  1. The name of the application
  2. The function to be loaded (the entry point to be loaded)
  3. Function used to activate (logic used to tell whether to load the app)

Next you need to create code for each app.

React application

Creates 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 id="Hello-from-React">Hello from React</h1>

export default App

Vue application

Create the following two in the src/vue directory 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>
  <p>
      </p>
<h1 id="Hello-from-Vue">Hello from Vue</h1>
  
</template>

Next, in Create an index.html file in the root directory of the program:

touch index.html

index.html

  
    <p></p>
    <p></p>
    <script></script>
  

Update Package.json with a script

Add in package.json Startup and build scripts:

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

Run the program

Execute the program by running start:

npm start

Now accessible via the following URL:

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

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

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

Summary

Except for the configuration at the beginning, other work is very easy. It would be nice if in the future Single-spa could add a CLI to handle boilerplate and initial project setup.

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

Original text: https://dev.to/dabit3/building-micro-frontends-with-react-vue-and-single-spa-52op

Author: Nader Dabit

Related recommendations:

2020 front-end vue interview questions summary (with answers)

Vue tutorial recommendation: The latest 5 vue.js video tutorial selections in 2020

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Create a micro frontend using React, Vue and Single SPA. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:dev. If there is any infringement, please contact admin@php.cn delete
实战:vscode中开发一个支持vue文件跳转到定义的插件实战:vscode中开发一个支持vue文件跳转到定义的插件Nov 16, 2022 pm 08:43 PM

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

5个常见的JavaScript内存错误5个常见的JavaScript内存错误Aug 25, 2022 am 10:27 AM

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

巧用CSS实现各种奇形怪状按钮(附代码)巧用CSS实现各种奇形怪状按钮(附代码)Jul 19, 2022 am 11:28 AM

本篇文章带大家看看怎么使用 CSS 轻松实现高频出现的各类奇形怪状按钮,希望对大家有所帮助!

Node.js 19正式发布,聊聊它的 6 大特性!Node.js 19正式发布,聊聊它的 6 大特性!Nov 16, 2022 pm 08:34 PM

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

浅析Vue3动态组件怎么进行异常处理浅析Vue3动态组件怎么进行异常处理Dec 02, 2022 pm 09:11 PM

Vue3动态组件怎么进行异常处理?下面本篇文章带大家聊聊Vue3 动态组件异常处理的方法,希望对大家有所帮助!

聊聊如何选择一个最好的Node.js Docker镜像?聊聊如何选择一个最好的Node.js Docker镜像?Dec 13, 2022 pm 08:00 PM

选择一个Node​的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

聊聊Node.js中的 GC (垃圾回收)机制聊聊Node.js中的 GC (垃圾回收)机制Nov 29, 2022 pm 08:44 PM

Node.js 是如何做 GC (垃圾回收)的?下面本篇文章就来带大家了解一下。

【6大类】实用的前端处理文件的工具库,快来收藏吧!【6大类】实用的前端处理文件的工具库,快来收藏吧!Jul 15, 2022 pm 02:58 PM

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft