# Monorepo Setup for Javascript, Typescript and React with NPM packages (1/4)

- URL: https://www.heissenberger.at/en/blog/monorepo-setup-javascript-typescript-react-npm-1/
- Language: en
- Published: 2021-02-03
- Tags: React JS, Monorepo, Lerna, Typescript, Javascript, NPM

> Setup an environment with independed npm packages for Javascript, Typescript and React components or libs which support all modern package formats

## 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](https://yarnpkg.com/) ([Workspaces](https://yarnpkg.com/lang/en/docs/workspaces/))
- [Lerna](https://lernajs.io/)
- [Microbundle](https://github.com/developit/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

1. [Setup a Monorepo for Javascript backend services](#part1)
2. [Add a Create React App frontend with a component libary](https://www.heissenberger.at/en/blog/monorepo-setup-javascript-typescript-react-npm-2/)
3. [Support Typescript in packages](https://www.heissenberger.at/en/blog/monorepo-setup-javascript-typescript-react-npm-3/)
4. [Deploy to private Github NPM registry](https://www.heissenberger.at/en/blog/monorepo-setup-javascript-typescript-react-npm-4/)

## 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/
```

<br/><br id="part1"/>

## 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:

```bash
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](https://yarnpkg.com/lang/en/docs/workspaces/)

```json
{
  "name": "ekzemplo",
  "version": "0.0.0",
  "license": "MIT",
  "private": true,
  "workspaces": ["packages/*"]
}
```

Add `lerna` and `microbundl` as [workspace dependencies `-W`](https://yarnpkg.com/en/docs/cli/add#toc-yarn-add-ignore-workspace-root-check-w) and initalize `lerna`:

```bash
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 `npmClient` and `useWorkspaces`
- remove attribute `workspaces` - lerna will use the definition from `packages.json`

```json
{
  "version": "independent",
  "npmClient": "yarn",
  "useWorkspaces": true
}
```

<br/><br/>

### Create the shared libary

each packages will need its own directory:

```bash
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 `version` in package.json to `0.0.0` to allow `lerna` to manage the version.
- add `"source": "src/index.js",` to tell `microbundle` about your entry file
- change `"main": "dist/index.js",` to `dist/` folder
- add `module`, `exports`, `unpkg` for modern formats (ESM bundle, ES2017)
- add `"type":"module"` to switch to ES6 module support (=allow `import from` statements)
- add `scripts` to rebuild on changes during development

```json
{
  "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`:

```bash
yarn add faker
```

then add `src/appfakes.js`

```javascript
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`

```javascript
export * from "./appfakes"
```

build the package in `dist/`:

```bash
yarn build
```

<br/><br/>

### create microservice events

```bash
mkdir -p services/ekzemplo-apievents/src
cd services/ekzemplo-apievents
yarn init -y
```

add dependencies:

- `express` - https server libary
- `ekzemplo-common` - local shared libary

```bash
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:

```javascript
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`:

```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:

```bash
yarn start
```

request the events from the api in your browser:
http://localhost:3011/events

you should get as a result

```json
[
  {
    "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"
  }
]
```

<br/><br/>

### create microservice users (ES6 module)

```bash
mkdir -p services/ekzemplo-apieusers/src
cd services/ekzemplo-apieusers
yarn init -y
```

add dependencies:

- `express` - https server libary
- `ekzemplo-common` - local shared libary

```bash
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:

```javascript
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

```json
{
  "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:

```bash
yarn start
```

request the users from the api in your browser:
http://localhost:3011/users

you should get as a result

```json
[
  {
    "id": "fc6af2ae-6457-4de6-8573-0e86ab609a15",
    "username": "Laurianne.Mertz37",
    "password": "pw"
  },
  {
    "id": "f331f161-27f0-4f53-aa46-b828573ac88b",
    "username": "Yasmeen.Frami88",
    "password": "pw"
  }
]
```

<br/><br/>

### Run all Services with one command

add this to the root `package.json`:

```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`

<br/><br/>

**next part: ** [Add a Create React App frontend with a component libary](https://www.heissenberger.at/en/blog/monorepo-setup-javascript-typescript-react-npm-2/)

[Write a response on Medium](https://medium.com/p/71d37c395b67/responses/show)
