Simplify your Node.js project with module aliases
- Published on
- /3 mins read/---
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.
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:
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:
tsconfig.json
Update 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:
module-alias
package
Install the This package resolves path aliases in JS files after they are compiled.
Install it with:
Configure it in
package.json
:package.json
Note that dist/
is the folder that contains your code after it has been built (depending on your configuration, it could be dist/
, build/
, etc.).
Finally, register the module in your app:
Import it only once in your project's start file (such as index.ts
, app.ts
, or server.ts
...).
Done
Now you can reload your IDE, start the project, and use aliases across your project.
VS Code supports this feature by reading the tsconfig.json
file. Simply reload it to use the feature.
Good luck!