Recently, I have been working on a pet project using Node.js on the backend to further my knowledge and prevent skill degradation during my free time. However, I encountered a frustrating issue with paths that many developers have likely experienced.
import { saveUser } from '../../../../../models/User'import homeController from '../../../../../controllers/home'
This code can be a headache for developers who need to determine how many folders to traverse to find the desired file. If you need to move a file to a different folder, you must update the path in all files that import the module .
But what if we could define aliases (i.e., shortcuts) for frequently imported modules throughout the entire project?
For example:
import { saveUser } from '@models/User'import homeController from '@controllers/home'
In which:
@models is equivalent to ./src/models/*
@controllers is equivalent to ./src/controllers/*.
The solution is quite simple with module-alias and a tsconfig.json configuration. Follow these instructions to set it up:
Update tsconfig.json
Open the tsconfig.json file and add the following configuration to the compilerOptions object:
Here, @controllers and @models are aliases for your modules (you can use any naming convention you like, and it does not have to start with @ — that's just the prefix I use to differentiate).
Now you can use the configured alias in your project, but you will encounter a module import error:
[Node] Error: Cannot find module '@models/User'
Install the module-alias package
This package resolves path aliases in JS files after they are compiled.
Install it with:
npm i --save module-alias # or yarn add module-alias