Monorepo Setup for Javascript, Typescript and React with NPM packages (1/4)
Executive brief
Setup an environment with independed npm packages for Javascript, Typescript and React components or libs which support all modern package formats.
Tooling
These are the tools we will use under the hood:
- Node.js >= v13 with ES6 module support
- Yarn (Workspaces)
- Lerna
- Microbundle
Goals
- reuse codeparts, react components and type definition between frontend and backend
- reuse codeparts, react components and type definition in other project as npm packages
- support mixed Javascript and Typescript development
- can be used for fullstack projects (frontend, api, libaries)
Sections
- Setup a Monorepo for Javascript backend services
- Add a Create React App frontend with a component libary
- Support Typescript in packages
- Deploy to private Github NPM registry
Example “ekzemplo” App Use Case
- As a User I can lists public events
- As a publisher I can login to the backend
- As a publisher I can create a new event
Architecture
- Website (React App)
- Administration Backend (React App)
- manage events api (Microservice)
- manage backend users api (Microservice)
- shared libary (libary)
this is the proposed directory structure :
ekzemplo
services/
ekzemplo-web/
ekzemplo-admin/
ekzemplo-apievents/
ekzemplo-apiusers/
packages/
ekzemplo-common/
ekzemplo-components/
1) Setup a Monorepo for Javascript backend service
Goals
share a utility libary between multiple microservices
Setup the repository
we need to create the repo root:
mkdir ekzemplo
cd ekzemplo
yarn init -yp
echo "node_modules" > .gitignore
Hint: ‘-y’: skip interactice session, ‘-p’: add private: true to the `package.json“
Open package.json in your editor:
- remove the attribute
main - set version to
0.0.0 - add workspaces
{
"name": "ekzemplo",
"version": "0.0.0",
"license": "MIT",
"private": true,
"workspaces": ["packages/*"]
}
Add lerna and microbundl as workspace dependencies -W and initalize lerna:
yarn add lerna microbundle --dev -W
yarn lerna init --independent
Lerna init creates the packages/ folder and a lerna.json file. The flag --independent sets the version filed in lerna.json to version each package independed.
Tipp (MacOS only)
exclude node_modules from TM backup
tmutil addexclusion $(pwd)/node_modules
Next, modify lerna.json to integrate yarn:
- add attributes
npmClientanduseWorkspaces - remove attribute
workspaces- lerna will use the definition frompackages.json
{
"version": "independent",
"npmClient": "yarn",
"useWorkspaces": true
}
Create the shared libary
each packages will need its own directory:
mkdir -p packages/ekzemplo-common/src
cd packages/ekzemplo-common
yarn init -y
to create a bundle which supports old and new bundle formats we change package.json to use microbundle in
- change the attribute
versionin package.json to0.0.0to allowlernato manage the version. - add
"source": "src/index.js",to tellmicrobundleabout your entry file - change
"main": "dist/index.js",todist/folder - add
module,exports,unpkgfor modern formats (ESM bundle, ES2017) - add
"type":"module"to switch to ES6 module support (=allowimport fromstatements) - add
scriptsto rebuild on changes during development
{
"name": "ekzemplo-common",
"version": "0.0.0",
"source": "/src/index.js",
"main": "dist/index.cjs",
"module": "dist/index.module.mjs",
"unpkg": "dist/index.umd.js",
"type": "module",
"license": "MIT",
"scripts": {
"start": "microbundle watch",
"build": "microbundle build"
}
}
The shared libary will provide a function to validate create fake users and events based on faker:
yarn add faker
then add src/appfakes.js
import faker from "faker"
export const event = () => {
return {
id: faker.random.uuid(),
name: faker.lorem.words(4),
date: faker.date.future(),
}
}
export const user = () => {
return {
id: faker.random.uuid(),
username: faker.internet.userName(),
password: "pw",
}
}
and src/index.js
export * from "./appfakes"
build the package in dist/:
yarn build
create microservice events
mkdir -p services/ekzemplo-apievents/src
cd services/ekzemplo-apievents
yarn init -y
add dependencies:
express- https server libaryekzemplo-common- local shared libary
yarn add express ekzemplo-common -W
Hint: do not forget -W to inform yarn to link the existing package from your monorepo
create a microservice which uses the CommonJS Module Syntax:
const express = require("express")
const appfaker = require("ekzemplo-common")
const app = express()
const port = 3010
const apiPath = "/events"
app.get(apiPath, (req, res) => {
let events = []
for (let index = 0; index < 10; index++) {
const Event = appfaker.event()
events.push(Event)
}
res.send(JSON.stringify(events))
})
app.listen(port, () => {
console.log(`microsoervice events listening at http://localhost:${port}${apiPath}`)
})
add a start command to package.json:
{
"name": "ekzemplo-apievents",
"version": "1.0.0",
"main": "./src/server.js",
"license": "MIT",
"dependencies": {
"ekzemplo-common": "^0.0.1",
"express": "^4.17.1"
},
"scripts": {
"start": "node src/server.js"
}
}
test the microservice:
yarn start
request the events from the api in your browser: http://localhost:3011/events
you should get as a result
[
{
"id": "aa4f1908-7805-41a3-a110-2440126eff60",
"name": "doloremque natus eius beatae",
"date": "2021-12-04T04:45:13.312Z"
},
{
"id": "f3fc0b0e-b448-4a28-92fa-fc539973d501",
"name": "nihil omnis tenetur qui",
"date": "2021-05-28T07:39:17.802Z"
}
]
create microservice users (ES6 module)
mkdir -p services/ekzemplo-apieusers/src
cd services/ekzemplo-apieusers
yarn init -y
add dependencies:
express- https server libaryekzemplo-common- local shared libary
yarn add express ekzemplo-common -W
Hint: do not forget -W to inform yarn to link the existing package from your monorepo
create a microservice which uses the ES6 Module Syntax:
import express from "express"
import { user } from "ekzemplo-common"
const app = express()
const port = 3011
const apiPath = "/users"
app.get(apiPath, (req, res) => {
let users = []
for (let index = 0; index < 10; index++) {
const User = user()
users.push(User)
}
res.send(JSON.stringify(users))
})
app.listen(port, () => {
console.log(`microsoervice users listening at http://localhost:${port}${apiPath}`)
})
add to package.json:
- add
"type":"module",for the ES6 module syntax - a start command
{
"name": "ekzemplo-apiusers",
"version": "1.0.0",
"main": "./src/server.js",
"type": "module",
"license": "MIT",
"dependencies": {
"ekzemplo-common": "^0.0.1",
"express": "^4.17.1"
},
"scripts": {
"start": "node src/server.js"
}
}
test the microservice:
yarn start
request the users from the api in your browser: http://localhost:3011/users
you should get as a result
[
{
"id": "fc6af2ae-6457-4de6-8573-0e86ab609a15",
"username": "Laurianne.Mertz37",
"password": "pw"
},
{
"id": "f331f161-27f0-4f53-aa46-b828573ac88b",
"username": "Yasmeen.Frami88",
"password": "pw"
}
]
Run all Services with one command
add this to the root package.json:
{
"name": "ekzemplo",
"version": "0.0.0",
"license": "MIT",
"main": "index.js",
"author": "Andreas Heissenberger <andreas@heissenberger.at>",
"private": true,
"workspaces": ["packages/*"],
"devDependencies": {
"lerna": "^3.22.1",
"microbundle": "https://github.com/aheissenberger/microbundle.git"
},
"scripts": {
"start": "lerna run start --parallel"
}
}
test it with yarn start
**next part: ** Add a Create React App frontend with a component libary