Chapter 4 module federation implementation of microapplications

4-1 Infrastructure -React

Base application code installation

// webpack5 
npm install webpack webpack-cli html-webpack-plugin css-loader style-loader babel-loader @babel/core  @babel/preset-env  @babel/preset-react  webpack-dev-server  -D 

npm install react react-dom 
Copy the code

Basic code:

// ======insex.html========
<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>RootReact</title>
</head>
<body>
  <! -- Add a line comment -->
  <div id="root"></div>
</body>
</html>
Copy the code
// ======insex.js========

import React from "react"
import ReactDom from "react-dom"
import App from "./App"
ReactDom.render(<App/>.document.getElementById('root'))


// ======App.js===========
import React from "react"
import User from "./User"


let App = () = > {
    return (
        <div>
            <h3>webpack55</h3>
            <User/>
        </div>)}export default App;


// ===== User.js==========
import React from "react"

const User = () = >{
  return (
    <div>
      UserList
    </div>)}export default User
Copy the code

4-2 Basic configuration webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // Entry, output, module, plugins mode, devServer

    // mode Indicates the working mode
    mode: 'development'.// Production, development, none

    / / the entry
    entry: './src/index.js'./ / export
    output: {
        filename: './bundle.js'.path: path.resolve(__dirname, 'dist')},/ / module
    module: {
        rules: [{test: /\.js$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader'.options: {
                            presets: [
                                '@babel/preset-env'.'@babel/preset-react']}}]},]},/ / the plugin
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'})]./ / the server
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        port: 3000.open: true}},Copy the code

Package. json startup command:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build":"webpack"."start":"webpack serve"
  },
Copy the code

4-3 Export microapplications

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// Import the module federated plug-in
const Mfp = require('webpack').container.ModuleFederationPlugin;

^^^^^^^^Codes^^^^^^^^^^^^^
   
    / / the plugin
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),
        // Instantiate the module federated plug-in
        new Mfp({
            // Specifies the packaged file name provided externally
            filename:'myuser.js'.// Micro application (module) name, similar to single-SPA team name
            name:'study'.exposes: {// A specific file can be used as a module,
                // Each application has a name and a specified code file
                // Name: the specific packaged code file
               './xx':'./src/User.js'.'./goods':'./src/Goods.js'}})].Copy the code

4-4 Import an application module

const Mfp = require('webpack').container.ModuleFederationPlugin    

/ / the plugin
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),

        new Mfp({
            // // Micro application (module) name, the name of the current module
            name:'roots'.// Import the module
            remotes: {// After the import, give the module a different name: "micro-application name @address/exported file name"
                one:"study@http://localhost:3001/myuser.js"}})].Copy the code

Used in components

// const xx = react.lazy (()=>import(" module alias/export file name "))
const Us = React.lazy(() = >import("one/xx"))
const Gos = React.lazy(() = >import("one/goods"))

let App = () = > {
    return (
        <div>
            <h3>webpack5 root</h3>
            <User/>
            <React.Suspense fallback="Loading app">
                <Us />
                <Gos />
            </React.Suspense>
        </div>)}export default App;
Copy the code

Modules 4-5 federally realize Vue3.0 micro-front-end architecture

Modulefederationvue3: Example of Vue3.0 micro-front-end architecture based on modulefederation implementation (gitee.com)

package.json

{
  "name": "@vue3-demo/layout"."private": true."version": "1.0.0"."scripts": {
    "start": "webpack serve"."serve": "serve dist -p 3001"."build": "webpack --mode production"."clean": "rm -rf dist"
  },
  "dependencies": {
    "@babel/core": "^ 7.13.16"."babel-loader": "^ 8.2.2"."serve": "^ 11.3.2." "."vue": 5 "" ^ 3.0.0 - rc.."vue-router": "^ 4.0.0"."vuex": "^ 4.0.0"
  },
  "devDependencies": {
    "@vue/compiler-sfc": "3.0.0"."css-loader": 5.2.4 ""."file-loader": "6.2.0"."html-webpack-plugin": "5.3.1"."mini-css-extract-plugin": "0.9.0"."url-loader": "4.1.1"."vue-loader": "16.0.0 - beta. 8"."webpack": "5.35.0"."webpack-dev-server": "3.11.2"."webpack-cli": "4.6.0"."sass": "^ 1.26.5"."sass-loader": "^ 8.0.2." "}}Copy the code

4-5-1 Exports modules in the home application

home\webpack.config.js

const { ModuleFederationPlugin } = require("webpack").container;

module.exports = (env = {}) = >({^ ^ ^ ^ ^ ^ ^........................... ^^^^^^^^^^^ plugins: [new VueLoaderPlugin(),

    // Module federation
    new ModuleFederationPlugin({
      name: "home".filename: "remoteEntry.js"./ / export
      exposes: {
        "./User": "./src/components/User".// "./Button": "./src/components/Button",}}}),]);Copy the code

Import 4-5-2 in the Layout application

layout\webpack.config.js

const { ModuleFederationPlugin } = require("webpack").container; .....................module.exports = (env = {}) = > ({
  
  plugins: [.....................new ModuleFederationPlugin({
      name: "layout".filename: "remoteEntry.js"./ / import
      remotes: {
        importUser: "home@http://localhost:3002/remoteEntry.js",},exposes: {},}),]});Copy the code

layout\src\views\About.vue

<template> <div class="about"> </p> <User /> </div> </template> <script> import {defineAsyncComponent} from "vue"; Const User = defineAsyncComponent(() => import("importUser/User")); export default { components: { User } }; </script>Copy the code

After writing the basic code and corresponding configuration, start the two application projects of Home and Layout respectively, you can see the content of User component in the Home application in the About of layout application.