Nest JS: Converting Relative path to Absolute Path

Amir Mustafa
5 min readOct 26, 2022

--

→ Whenever we are writing Codes, it is good practice to use an absolute path instead of a relative path.

→ Nest Js is a progressive Node JS framework.

→ Here we cannot use absolute path directly as it is written in TypeScript and does not support much with direct absolute path.

→ In this article we will quickly see how to convert relative path to absolute path.

Why Relative Path is an issue?

If we are working in complex directory structure. Using same ../../src like in different multi-level will be complex and not reusable.

Solution:

Using Absolute Path. We can use same path in any directory level.

Pre-requisite:

Basic understanding of Nest.js module creation. This is somewhere similar to Angular.

The steps are simple and be understood with below steps.

Relative Path:

tag.module.js

import { Module } from '@nestjs/common';import { TagController } from './tag.controller'; // RELATIVE PATHimport { TagService } from './tag.service';@Module({controllers: [TagController],providers: [TagService],})export class TagModule {}

tag.controller.js

import { Controller, Get } from '@nestjs/common';import { TagService } from './tag.service'; // RELATIVE PATH@Controller('tags')
export class TagController {
constructor(private readonly tagService: TagService) {}@Get()findAll(): string[] {return this.tagService.findAll();}}

tag.service.js

import { Injectable } from '@nestjs/common';@Injectable()export class TagService {  findAll(): string[] {    return ['dragons', 'coffee', 'weathers'];  }}

→ We cannot convert directly to an absolute path like Express.js as we are using Typescript.

Converting to Absolute Path:

→ As the Typescript layer is there we have to manage the absolute path for both Typescript and Javascript transpired code.

STEP 1: Typescript Fix:

→ Open tsconfig.ts code. Add paths variable as shown below

→ Typescript code resides in src directory.

"paths": {  "@app/*": ["./src/*"]"}

STEP 2: Javascript Fix:

For this, we have to install one package

https://www.npmjs.com/package/module-aliasyarn add module-alias

→ For Typescript, we already handled in tsconfig.ts file. For Javascript we do with this package.

STEP 3: Open package.json file. Add below lines:

{"name": "nestjs-medium-clone","version": "0.0.1","format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"","start": "nodemon",    // NEW LINE ADDED"test:e2e": "jest --config ./test/jest-e2e.json"},"dependencies": {"@nestjs/common": "^9.0.0","@nestjs/core": "^9.0.0","@nestjs/platform-express": "^9.0.0",},"devDependencies": {"@nestjs/cli": "^9.0.0","@nestjs/schematics": "^9.0.0","@nestjs/testing": "^9.0.0","@types/express": "^4.17.13","@types/jest": "28.1.8","@types/node": "^16.0.0","@types/supertest": "^2.0.11","@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": "28.1.3","prettier": "^2.3.2","source-map-support": "^0.5.20","supertest": "^6.1.3","ts-jest": "28.0.8","ts-loader": "^9.2.3","ts-node": "^10.0.0","tsconfig-paths": "4.1.0","typescript": "^4.7.4"},"jest": {"moduleFileExtensions": ["js","json","ts"],"rootDir": "src","testRegex": ".*\\.spec\\.ts$","transform": {"^.+\\.(t|j)s$": "ts-jest"},"collectCoverageFrom": ["**/*.(t|j)s"],"coverageDirectory": "../coverage","testEnvironment": "node"},"_moduleAliases": { // NEW LINE ADDED  "@app": "./dist" // PATH TO JS TRANSPILED FILE}}

STEP 4: Create nodemon.json file in root level:

→ In this step we are actually adding watch mode. Any change will be directly reflected without restarting the node server.

→ This is the same package we use in Express.js.

nodemon.json

{  "watch": ["src"],  "ext": "ts",  "exec": "IS_TS_NODE=true ts-node -r tsconfig-paths/register src/main.ts"}

STEP 5: Adding below line for module alias registry file

We have to write below code in entry file of the application as written in below package.

https://www.npmjs.com/package/module-alias

main.ts

if(!process.env.IS_TS_NODE) {
require('module-alias/register');
}

→ Javascript transpiles only in production mode. Hence adding above lines for production only.

STEP 6: Finally replacing Relative path with Absolute path:

Old Path:

import { AppController } from './app.controller';import { AppService } from './app.service';import { TagModule } from './tag/tag.module';

New Path:

import { AppController } from '@app/app.controller';import { AppService } from '@app/app.service';import { TagModule } from '@app/tag/tag.module';

→ Now we can use this line throughout the application without thinking of the directory level of the file.

For TS:

@app -->  './src'

For JS:

@app -->  './dist'

→ Hurray our absolute path is configured successfully.

→ We now hit Nest.js route and getting response using absolute path.

GitHub:

https://bit.ly/3gXcY2A

Closing Thoughts:

Working on the initial levels of projects using a relative path may be fine. If we are working on a complex project using an absolute path is a good practice as all the paths are reusable.

Thank you for reading till the end 🙌 . If you enjoyed this article or learned something new, support me by clicking the share button below to reach more people and/or give me a follow on Twitter and subscribe Happy Learnings !! to see some other tips, articles, and things I learn about and share there.

--

--

Amir Mustafa

JavaScript Specialist | Consultant | YouTuber 🎬. | AWS ☁️ | Docker 🐳 | Digital Nomad | Human. Connect with me on https://www.linkedin.com/in/amirmustafa1/