6 min read
Original source

Introduction to a monorepo with Lerna and Yarn workspaces

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…

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:mkdir nestjs-monorepo && cd nestjs-monorepo npx 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. lerna.json { "packages": [ "packages/*" ], "version": "0.0.0" }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. lerna.json { "packages": [ "libraries/*", "applications/*" ], "version": "0.0.0" } 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. lerna.json { "packages": [ "libraries/*", "applications/*" ], "version": "0.0.0", "npmClient": "yarn", "useWorkspaces": true } 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. tsconfig.json { "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "target": "es2017", "sourceMap": true, "outDir": "./dist", "baseUrl": "./", "incremental": true, "skipLibCheck": true, "strictNullChecks": false, "noImplicitAny": false, "strictBindCallApply": false, "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false, "strict": true } } tsconfig.build.json { "extends": "./tsconfig.json", "exclude": ["node_modules", "dist", "test", "**/*spec.ts"] } .eslintrc.json module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', ], root: true, env: { node: true, jest: true, }, ignorePatterns: ['.eslintrc.js'], rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-explicit-any': 'off', }, }; .prettierrc { "singleQuote": true, "trailingComma": "all" } jest.config.js module.exports = { moduleFileExtensions: [ 'js', 'json', 'ts' ], rootDir: 'src', testRegex: '.*\\.spec\\.ts$', transform: { '^.+\\.(t|j)s$': 'ts-jest' }, collectCoverageFrom: [ '**/*.(t|j)s' ], coverageDirectory: '../coverage', testEnvironment: 'node' } 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: package.json { "name": "@nestjs-monorepo", "private": true, "devDependencies": { "lerna": "^4.0.0", "@typescript-eslint/eslint-plugin": "^5.0.0", "@typescript-eslint/parser": "^5.0.0", "eslint": "^8.0.1", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^4.0.0", "jest": "^27.2.5", "prettier": "^2.3.2", "source-map-support": "^0.5.20", "ts-jest": "^27.0.3", "ts-loader": "^9.2.3", "ts-node": "^10.0.0", "tsconfig-paths": "^3.10.1", "typescript": "^4.3.5" }, "workspaces": ["applications/*", "libraries/*"] } 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.mkdir applications && mkdir applications/core applications/core/tsconfig.json { "extends": "../../tsconfig.json" } applications/core/tsconfig.build.json { "extends": "../../tsconfig.build.json" } applications/core/.eslintrc.js module.exports = { extends: ['../../.eslintrc.js'], }; applications/core/jest.config.js const config = require('../../jest.config'); module.exports = { ...config } applications/core/package.json { "name": "@nestjs-monorepo/core", "private": true, "version": "0.0.1", "scripts": { "prebuild": "rimraf dist", "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start": "nest start", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest" }, "dependencies": { "@nestjs/common": "^8.0.0", "@nestjs/core": "^8.0.0", "@nestjs/platform-express": "^8.0.0", "reflect-metadata": "^0.1.13", "rimraf": "^3.0.2" }, "devDependencies": { "@nestjs/cli": "^8.0.0", "@nestjs/schematics": "^8.0.0", "@nestjs/testing": "^8.0.0", "@types/express": "^4.17.13", "@types/jest": "^27.0.1", "@types/node": "^16.0.0", "@types/supertest": "^2.0.11", "supertest": "^6.1.3" } }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.. ├── applications │   ├── core │   │   ├── ... │   └── emails-subscriptions │   ├── docker-compose.yml │   ├── docker.env │   ├── jest.config.js │   ├── package.json │   ├── src │   │   ├── app.module.ts │   │   ├── database │   │   │   ├── database.module.ts │   │   │   └── postgresErrorCode.enum.ts │   │   ├── main.ts │   │   └── subscribers │   │   ├── dto │   │   │   └── createSubscriber.dto.ts │   │   ├── subscriber.entity.ts │   │   ├── subscribers.controller.ts │   │   ├── subscribers.module.ts │   │   └── subscribers.service.ts │   ├── tsconfig.build.json │   └── tsconfig.jsonThe crucial logic that we aim to use is in the subscribers.controller.ts file. For a full example visit this repository. applications/email-subscriptions/src/subscribers/subscribers.controller.ts import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; import CreateSubscriberDto from './dto/createSubscriber.dto'; import { SubscribersService } from './subscribers.service'; @Controller() export class SubscribersController { constructor( private readonly subscribersService: SubscribersService, ) {} @MessagePattern({ cmd: 'add-subscriber' }) addSubscriber(subscriber: CreateSubscriberDto) { return this.subscribersService.addSubscriber(subscriber); } @MessagePattern({ cmd: 'get-all-subscribers' }) getAllSubscribers() { return this.subscribersService.getAllSubscribers(); } }Thanks to doing the above, we can use our microservice in the core application. applications/core/src/email-subscriptions/emailSubscriptions.controller.ts import { Body, Controller, Get, Post, Inject, } from '@nestjs/common'; import CreateSubscriberDto from './dto/createSubscriber.dto'; import { ClientProxy } from '@nestjs/microservices'; @Controller('email-subscriptions') export default class EmailSubscriptionsController { constructor( @Inject('SUBSCRIBERS_SERVICE') private subscribersService: ClientProxy, ) {} @Get() async getSubscribers() { return this.subscribersService.send({ cmd: 'get-all-subscribers' }, '') } @Post() async createPost(@Body() subscriber: CreateSubscriberDto) { return this.subscribersService.send({ cmd: 'add-subscriber' }, subscriber) } }After defi

Introduction to a monorepo with Lerna and Yarn workspaces | NestJS.io