/09-client-side-composition

Sample project for the "client-side composition" pattern of ch. 9.

Primary LanguageJavaScript

Chapter 09

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/09-client-side-composition.git

Go to the repository's directory and start the application, which installs also all dependencies:

./run.sh

Steps

Follow these steps to implement the same from scratch.

  1. Start with the app shell, create a new directory for it and run
npm init -y
  1. Install the dependencies
npm i http-server --save-dev
  1. Create some static resources such as an index.html and a style.css file in a new public folder, most importantly reference the MFs via their custom components and script source:
<product-page id="app"></product-page>
<script src="http://localhost:2001/product-page.js"></script>
  1. Run the HTTP server, e.g., http-server ./public --port 1234

  2. Now create the MFs, e.g., the red microfrontend

  3. Create a directory for each microfrontend, initializing it as a new Node.js project:

npm init -y
  1. Install the dependencies, mostly for development:
npm i file-loader http-server style-loader webpack webpack-cli webpack-dev-server --save-dev
  1. Create a webpack.config.js as shown - keep in mind that the public path should be set to the path of the server exposing the microfrontend (e.g., http://localhost:2001/ for red)

  2. Write the MFs in form of custom web components such as

// reference resources by importing them
import "./style.css";
import image from "./image.jpg";

class MyComponent extends HTMLElement {
  constructor() {
    super();
    // initial rendering below
    this.innerHTML = ``;
  }

  static get observedAttributes() {
    // mark which attribute(s) to observe
    return [];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    // react to changes
  }
}

customElements.define("my-component", MyComponent);
  1. Build the MF using Webpack
npx webpack --mode production
  1. For debugging purposes you could just run a simple HTTP server to expose the MF
npx http-server dist --port 2001