Thursday, June 23, 2022

How to quickly set up a shared library for Micro-Frontend application?

When we start the Micro-Frontend application development. we can use Turborepo to setup the project by 

executing the following command in the CMD window or Terminal in the VS Code.   

npx create-turbo@latest

By default, the project will create a ui inside the packages folder for crosss project sharing.









if you want to create other sharing library or context project, then we just have to copy the entire ui folder and rename it to store (which is the state-management for the entire application). we can run the following command from the parent level of ui, which should packages folder.

cp -rf ui store

now open the package.json file inside the store folder to modify the following information.

name: "store"

remove all libraries in the dependenices section  and unrelated libraries in the devdependencies section.

then add zutand for state management.

{
  "name": "ui",
  "version": "0.0.0",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "license": "MIT",
  "scripts": {
    "dev": "tsc --watch --outDir dist",
    "build": "tsc --outDir dist",
    "lint": "eslint *.ts*"
  },
  "devDependencies": {
    "@types/react": "^18.0.9",
    "@types/react-dom": "^18.0.5",
    "eslint": "^7.32.0",
    "eslint-config-custom": "workspace:*",
    "react": "^18.1.0",
    "tsconfig": "workspace:*",
    "store": "workspace:*",
    "typescript": "^4.5.2"
  },
  "dependencies": {
    "@mantine/core": "^4.2.6",
    "@mantine/hooks": "^4.2.6",
    "react-router-dom": "^6.3.0"
  }
}

now the modified package.json should looks like the one below


{
  "name": "store",
  "version": "0.0.0",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "license": "MIT",
  "scripts": {
    "dev": "tsc --watch --outDir dist",
    "build": "tsc --outDir dist",
    "lint": "eslint *.ts*"
  },
  "devDependencies": {
    "@types/react": "^18.0.9",
    "@types/react-dom": "^18.0.5",
    "eslint": "^7.32.0",
    "eslint-config-custom": "workspace:*",
    "react": "^18.1.0",
    "tsconfig": "workspace:*",
    "typescript": "^4.5.2"
  },
  "dependencies": {
    "zustand": "4.0.0-rc.1"
  }
}

 

 You should run pnpm i to link all packages together.  Now we should have a share Store acrosss all projects in our MFE application.








No comments:

Post a Comment