【微前端】用React、Vue和Single-spa打造微前端

Chinese, Simplified

single-spa 用于前端微服务的javascript框架

在过去的几周里,围绕微前沿(一些负面的,一些正面的)已经有了大量的讨论。

有一个tweet,真正吸引我的目光从乔尔丹宁‏,single-spa:

Funny how the many of the people recently criticizing #microfrontends (1) haven’t tried them, (2) don’t understand what they are, and (3) have attacked microfrontends and the people using them with almost a bully-like sarcasm.

I’m one of the main popularizers of them - AMA

 

当我看到一些新的和有争议的东西,像这样,我总是想自己尝试一下,看看所有的炒作是关于什么的,也让我可以形成自己的观点对这个主题。

这引导我创建了一个微前端应用程序,它呈现了两个单独的React应用程序和一个Vue应用程序。

在本教程中,我将分享我所学到的知识,并向您展示如何构建一个由React和Vue应用程序组成的微前端应用程序。

要查看此应用程序的最终代码,请单击这里。

single-spa

我们将使用的工具来创建我们的项目是单SPA -一个javascript框架的前端微服务。

单SPA允许您在单页面应用程序中使用多个框架,允许您根据功能拆分代码,并具有Angular、React和Vue。js等应用都生活在一起。

您可能已经习惯了Create React应用程序CLI和Vue CLI。使用这些工具,您可以快速启动整个项目,完成webpack配置、依赖项和样板文件。

如果您习惯了这种简单的设置,那么第一部分可能有些不和谐。这是因为我们将从头开始创建所有内容,包括安装所需的所有依赖项,以及从头开始创建webpack和babel配置。

如果您仍然好奇Single SPA是做什么的,或者为什么您可能想要使用微前端架构来构建,请查看这个视频。

开始

你需要做的第一件事是创建一个新的文件夹来保存应用程序,并切换到目录:

mkdir single-spa-app

cd single-spa-app

 

接下来,我们将初始化一个新包。json文件:

npm init -y

现在,这是有趣的部分。我们将安装此项目所需的所有依赖项。我将把它们分成不同的步骤。

安装普通的依赖关系

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

 

安装 babel 依赖

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

 

安装 webpack 依赖

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

现在,所有依赖项都已安装,我们可以创建文件夹结构。

应用程序的主代码将位于src目录中。这个src目录将为每个应用程序保存子文件夹。让我们继续在src文件夹中创建react和vue应用程序文件夹:

mkdir src src/vue src/react

现在,我们可以为webpack和babel创建配置。

创建webpack配置

在主应用程序的根目录下,用以下代码创建一个webpack.config.js文件:

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

 

创建babel 配置

在主应用程序的根目录下,用下面的代码创建一个.babelrc文件:

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

初始化Single-spa

注册应用程序是我们告诉single-spa何时以及如何引导、挂载和卸载应用程序的方式。

在webpack.config.js文件中,我们将入口点设置为single-spa.config.js。

让我们继续在项目的根目录中创建该文件并配置它。

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();

这个文件是您注册所有应用程序的地方,这些应用程序将是主单页应用程序的一部分。每次调用registerApplication都会注册一个新应用程序,并接受三个参数:

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

接下来,我们需要为每个应用程序创建代码。

React 应用

在src/react中,创建以下两个文件:

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应用

在src/vue中,创建以下两个文件:

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>

接下来,在应用程序的根目录中创建index.html文件:

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>

更新Package.json使用脚本

要运行这个应用程序,让我们在package.json中添加start脚本和build脚本:

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

运行应用程序

要运行该应用程序,请运行start脚本:

npm start

现在,你可以访问以下网址:

# renders both apps
http://localhost:8080/

# renders only react
http://localhost:8080/react

# renders only vue
http://localhost:8080/vue

要查看此应用程序的最终代码,请单击这里

结论

总的来说,除了所有的初始样板设置外,设置这个项目相当简单。

我认为,在未来,如果能有某种CLI来处理大部分样板文件和初始项目设置,那就太好了。

如果您需要这种类型的架构,那么Single-spa无疑是目前最成熟的方式,并且非常适合您的工作。

 

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

本文:http://pub.intelligentx.net/building-micro-frontends-react-vue-and-single-spa

讨论:请加入知识星球或者小红圈【首席架构师圈】

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