Monorepo is an approach in which we store multiple projects in the same repository. It is common across big tech companies, such as Uber or Google. Even NestJS manages its source code in a monorepo with Lerna.
When we store all of our code in a single repository, it might be easier to understand how different parts of our systems relate to each other. Also, having all of our applications in one place can endorse sharing the code. Good examples are models and utility functions.
While the monorepos have advantages, we must avoid making our codebase messy. This article uses Lerna to manage our monorepo while creating a NestJS project. You can view all of the code from this article in this repository.
Starting a project with Lerna
Let’s kickstart our project with Lerna:
1mkdir nestjs-monorepo && cd nestjs-monorepo
2npx lerna init && npm installRunning lerna init does a few things for us:
- creates a new project with package.json containing lerna in devDependencies,
- defines a lerna.json file with a basic configuration,
- adds a packages directory where, by default, our apps go.
Let’s look at the lerna.json file created by the above command.
1{
2 "packages": [
3 "packages/*"
4 ],
5 "version": "0.0.0"
6}With the packages array, we can define directories where we want to define our applications. The version string is the current version of our repository.
Two approaches to versioning
With Lerna, we can choose one of the two approaches to versioning.
Fixed mode
By default, Lerna uses the fixed mode and uses a single version for the whole repository. Doing that binds the versions of all our packages. When changing the code one package and publishing a new version, we bump the version in all our packages. It is a straightforward approach but might result in unnecessary version changes for some of our packages. Since this is the default versioning mode, we use it in this article.
Independent mode
Lerna allows us to specify package versions separately for every package in the independent mode. Every time we publish, we need to establish a new version of each package that changed. Also, when using the independent mode, we need to specify "version": "independent" in our lerna.json.
Preparing the environment
In our case, we want to separately store applications such as microservices and libraries, such as reusable utilities. To do that, we need to modify our lerna.json.
1{
2 "packages": [
3 "libraries/*",
4 "applications/*"
5 ],
6 "version": "0.0.0"
7}Yarn workspaces
The workspaces feature built into Yarn works by optimizing the installation of dependencies for multiple projects at once. Every project that we create in our monorepo is a separate workspace. The dependencies across workspaces are linked together and depend on one another. The above feature is very commonly used with Lerna.
1{
2 "packages": [
3 "libraries/*",
4 "applications/*"
5 ],
6 "version": "0.0.0",
7 "npmClient": "yarn",
8 "useWorkspaces": true
9}Defining ESLint and TypeScript configuration
Before defining our first package, let’s define a TypeScript and ESlint configuration that we will use in every project we have.
1{
2 "compilerOptions": {
3 "module": "commonjs",
4 "declaration": true,
5 "removeComments": true,
6 "emitDecoratorMetadata": true,
7 "experimentalDecorators": true,
8 "allowSyntheticDefaultImports": true,
9 "target": "es2017",
10 "sourceMap": true,
11 "outDir": "./dist",
12 "baseUrl": "./",
13 "incremental": true,
14 "skipLibCheck": true,
15 "strictNullChecks": false,
16 "noImplicitAny": false,
17 "strictBindCallApply": false,
18 "forceConsistentCasingInFileNames": false,
19 "noFallthroughCasesInSwitch": false,
20 "strict": true
21 }
22}1{
2 "extends": "./tsconfig.json",
3 "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
4}1module.exports = {
2 parser: '@typescript-eslint/parser',
3 parserOptions: {
4 project: 'tsconfig.json',
5 sourceType: 'module',
6 },
7 plugins: ['@typescript-eslint/eslint-plugin'],
8 extends: [
9 'plugin:@typescript-eslint/recommended',
10 'plugin:prettier/recommended',
11 ],
12 root: true,
13 env: {
14 node: true,
15 jest: true,
16 },
17 ignorePatterns: ['.eslintrc.js'],
18 rules: {
19 '@typescript-eslint/interface-name-prefix': 'off',
20 '@typescript-eslint/explicit-function-return-type': 'off',
21 '@typescript-eslint/explicit-module-boundary-types': 'off',
22 '@typescript-eslint/no-explicit-any': 'off',
23 },
24};1{
2 "singleQuote": true,
3 "trailingComma": "all"
4}1module.exports = {
2 moduleFileExtensions: [
3 'js',
4 'json',
5 'ts'
6 ],
7 rootDir: 'src',
8 testRegex: '.*\\.spec\\.ts$',
9 transform: {
10 '^.+\\.(t|j)s$': 'ts-jest'
11 },
12 collectCoverageFrom: [
13 '**/*.(t|j)s'
14 ],
15 coverageDirectory: '../coverage',
16 testEnvironment: 'node'
17}In all of the above configuration files, I’m mostly using the default values created by NestJS CLI.
We can put the dependencies that we want to use in every package into the global package.json:
1{
2 "name": "@nestjs-monorepo",
3 "private": true,
4 "devDependencies": {
5 "lerna": "^4.0.0",
6 "@typescript-eslint/eslint-plugin": "^5.0.0",
7 "@typescript-eslint/parser": "^5.0.0",
8 "eslint": "^8.0.1",
9 "eslint-config-prettier": "^8.3.0",
10 "eslint-plugin-prettier": "^4.0.0",
11 "jest": "^27.2.5",
12 "prettier": "^2.3.2",
13 "source-map-support": "^0.5.20",
14 "ts-jest": "^27.0.3",
15 "ts-loader": "^9.2.3",
16 "ts-node": "^10.0.0",
17 "tsconfig-paths": "^3.10.1",
18 "typescript": "^4.3.5"
19 },
20 "workspaces": ["applications/*", "libraries/*"]
21}Make sure to also add "workspaces": ["applications/*", "libraries/*"].
Creating our first packages
Thanks to defining the global configuration in the above way, we can now define our first package that uses the global configuration.
1mkdir applications && mkdir applications/core1{
2 "extends": "../../tsconfig.json"
3}1{
2 "extends": "../../tsconfig.build.json"
3}1module.exports = {
2 extends: ['../../.eslintrc.js'],
3};1const config = require('../../jest.config');
2
3module.exports = {
4 ...config
5}1{
2 "name": "@nestjs-monorepo/core",
3 "private": true,
4 "version": "0.0.1",
5 "scripts": {
6 "prebuild": "rimraf dist",
7 "build": "nest build",
8 "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
9 "start": "nest start",
10 "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
11 "test": "jest"
12 },
13 "dependencies": {
14 "@nestjs/common": "^8.0.0",
15 "@nestjs/core": "^8.0.0",
16 "@nestjs/platform-express": "^8.0.0",
17 "reflect-metadata": "^0.1.13",
18 "rimraf": "^3.0.2"
19 },
20 "devDependencies": {
21 "@nestjs/cli": "^8.0.0",
22 "@nestjs/schematics": "^8.0.0",
23 "@nestjs/testing": "^8.0.0",
24 "@types/express": "^4.17.13",
25 "@types/jest": "^27.0.1",
26 "@types/node": "^16.0.0",
27 "@types/supertest": "^2.0.11",
28 "supertest": "^6.1.3"
29 }
30}Because the above dependencies are defined in the applications/core/package.json file and not in the global package.json, they will be installed just for the core application.
Adding multiple packages
We’ve created a simple microservice in part #18 of this series. Let’s define the email-subscriptions application in a similar way to the core app.
1.
2├── applications
3│ ├── core
4│ │ ├── ...
5│ └── emails-subscriptions
6│ ├── docker-compose.yml
7│ ├── docker.env
8│ ├── jest.config.js
9│ ├── package.json
10│ ├── src
11│ │ ├── app.module.ts
12│ │ ├── database
13│ │ │ ├── database.module.ts
14│ │ │ └── postgresErrorCode.enum.ts
15│ │ ├── main.ts
16│ │ └── subscribers
17│ │ ├── dto
18│ │ │ └── createSubscriber.dto.ts
19│ │ ├── subscriber.entity.ts
20│ │ ├── subscribers.controller.ts
21│ │ ├── subscribers.module.ts
22│ │ └── subscribers.service.ts
23│ ├── tsconfig.build.json
24│ └── tsconfig.jsonThe crucial logic that we aim to use is in the subscribers.controller.ts file.
For a full example visit this repository.
1import { Controller } from '@nestjs/common';
2import { MessagePattern } from '@nestjs/microservices';
3import CreateSubscriberDto from './dto/createSubscriber.dto';
4import { SubscribersService } from './subscribers.service';
5
6@Controller()
7export class SubscribersController {
8 constructor(
9 private readonly subscribersService: SubscribersService,
10 ) {}
11
12 @MessagePattern({ cmd: 'add-subscriber' })
13 addSubscriber(subscriber: CreateSubscriberDto) {
14 return this.subscribersService.addSubscriber(subscriber);
15 }
16
17 @MessagePattern({ cmd: 'get-all-subscribers' })
18 getAllSubscribers() {
19 return this.subscribersService.getAllSubscribers();
20 }
21}Thanks to doing the above, we can use our microservice in the core application.
1import {
2 Body,
3 Controller,
4 Get,
5 Post,
6 Inject,
7} from '@nestjs/common';
8import CreateSubscriberDto from './dto/createSubscriber.dto';
9import { ClientProxy } from '@nestjs/microservices';
10
11@Controller('email-subscriptions')
12export default class EmailSubscriptionsController {
13 constructor(
14 @Inject('SUBSCRIBERS_SERVICE') private subscribersService: ClientProxy,
15 ) {}
16
17 @Get()
18 async getSubscribers() {
19 return this.subscribersService.send({
20 cmd: 'get-all-subscribers'
21 }, '')
22 }
23
24 @Post()
25 async createPost(@Body() subscriber: CreateSubscriberDto) {
26 return this.subscribersService.send({
27 cmd: 'add-subscriber'
28 }, subscriber)
29 }
30}After defining both core and emails-subscriptions applications, our current file structure looks like that:
1.
2├── applications
3│ ├── core
4│ │ ├── jest.config.js
5│ │ ├── package.json
6│ │ ├── src
7│ │ │ ├── app.module.ts
8│ │ │ ├── email-subscriptions
9│ │ │ │ ├── dto
10│ │ │ │ │ └── createSubscriber.dto.ts
11│ │ │ │ ├── emailSubscriptions.controller.ts
12│ │ │ │ └── emailSubscriptions.module.ts
13│ │ │ └── main.ts
14│ │ ├── tsconfig.build.json
15│ │ └── tsconfig.json
16│ └── emails-subscriptions
17│ ├── docker-compose.yml
18│ ├── docker.env
19│ ├── jest.config.js
20│ ├── package.json
21│ ├── src
22│ │ ├── app.module.ts
23│ │ ├── database
24│ │ │ ├── database.module.ts
25│ │ │ └── postgresErrorCode.enum.ts
26│ │ ├── main.ts
27│ │ └── subscribers
28│ │ ├── dto
29│ │ │ └── createSubscriber.dto.ts
30│ │ ├── subscriber.entity.ts
31│ │ ├── subscribers.controller.ts
32│ │ ├── subscribers.module.ts
33│ │ └── subscribers.service.ts
34│ ├── tsconfig.build.json
35│ └── tsconfig.json
36├── jest.config.js
37├── lerna-debug.log
38├── lerna.json
39├── package.json
40├── tsconfig.build.json
41├── tsconfig.json
42└── yarn.lockInstalling all dependencies and running scripts
Even though we have more than one package.json in our project, we can install our dependencies with one command using the npx lerna bootstrap command. Doing the above creates three node_modules directories for us. One of them is at the root of our project, and the other is for the core and emails-subscriptions packages.
Once we install all of our dependencies, we can run npx lerna run <script> to run a particular script in all packages. For example, running npx lerna lint runs ESLint in both core and emails-subscriptions packages.
Summary
In this article, we’ve gone through the basics of using NestJS with Lerna. We’ve learned about different approaches to versioning we can implement and how to add Yarn workspaces to our configuration. We’ve also created reusable TypeScript, ESLint, and Jest configurations. On top of that, we’ve built a project that defines two applications. Within them, it establishes a connection to a microservice.
There is much more we can write on the topic of managing monorepos with Lerna, so stay tuned!