Skip to content

Sample project "web approach to microfrontends" of ch. 6.

Notifications You must be signed in to change notification settings

ArtOfMicrofrontends/06-web-approach

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Chapter 06

Prerequisites

The following software is required to run the sample:

  • Git
  • Node.js
  • NPM
  • Bash

Running

Clone the repository:

git clone https://github.com/ArtOfMicrofrontends/06-web-approach.git

Go to the repository's directory and run NPM install in each subdirectory:

cd mf-1
npm install
cd ..

cd mf-2
npm install
cd ..

cd mf-gw
npm install
cd ..

Now start the application:

./run.sh

Steps

Follow these steps to implement the same from scratch.

  1. Create the microfrontends
mkdir mf-1 && cd mf-1 && npm init -y && cd ..
mkdir mf-2 && cd mf-2 && npm init -y && cd ..
  1. Add dependencies to run the views
cd mf-1 && npm i http-server --save-dev && cd ..
cd mf-2 && npm i http-server --save-dev && cd ..
  1. Add script to start the local server, e.g., in the package.json of mf-1
{
    // ...
    "scripts": {
        "start": "http-server ./views --port 2001",
        // ...
    }
}
  1. Write some index.html in mf-1/views/mf1 and mf-2/views/mf2. The content can be as simple as:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MF-1</title>
</head>
<body>
<h1>This is microfrontend 1.</h1>
<a href="/mf2">Go to MF2</a>
</body>
</html>
  1. Add a gateway service:
mkdir mf-gw && cd mf-gw && npm init -y && cd ..
cd mf-gw && npm i http-proxy-middleware express --save && cd ..
  1. Define the gateway, which can be as simple as:
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");

const app = express();
const port = process.env.PORT || 1234;

const targets = {
  "/mf1": "http://localhost:2001",
  "/mf2": "http://localhost:2002",
};

app.get("/", (_, res) => res.redirect(Object.keys(targets)[0]));

Object.keys(targets).forEach((prefix) => {
  app.use(
    prefix,
    createProxyMiddleware({
      target: targets[prefix],
      changeOrigin: true,
    })
  );
});

app.get("*", (_, res) => res.status(404).send("Page not found."));

app.listen(port, () => {
  console.log(`Microfrontend gateway running at ${port}.`);
});
  1. Add code to run all microfrontends and the gateway.
echo "#!/bin/bash" > run.sh
echo "(trap 'kill 0' SIGINT; (cd mf-gw && npm start) & (cd mf-1 && npm start) & (cd mf-2 && npm start))" >> run.sh
chmod +x run.sh
  1. Run the solution
./run.sh
  1. Play around with assets, links, and fragments.

  2. Add a linking directory to the gateway.

About

Sample project "web approach to microfrontends" of ch. 6.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published