The following software is required to run the sample:
- Git
- Node.js
- NPM
- Bash
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
Follow these steps to implement the same from scratch.
- Create the microfrontends
mkdir mf-1 && cd mf-1 && npm init -y && cd ..
mkdir mf-2 && cd mf-2 && npm init -y && cd ..
- 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 ..
- Add script to start the local server, e.g., in the package.json of
mf-1
{
// ...
"scripts": {
"start": "http-server ./views --port 2001",
// ...
}
}
- Write some index.html in
mf-1/views/mf1
andmf-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>
- 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 ..
- 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}.`);
});
- 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
- Run the solution
./run.sh
-
Play around with assets, links, and fragments.
-
Add a linking directory to the gateway.