How to have path alias in Node.js ?
Node.js has tons of modules that can be very hard to deal with. Thus, it’s a good practice to have a neat and well-defined directory structure.
In this article, we are going to deal with a problem that involves the Node.js modules. Let’s first understand what is the need to have path alias.
There are a lot of dependencies, modules, and relative paths that we have to deal with while working with Node.js. Typing paths and Importing Node.js modules is error-prone and can be tiring. Code-completion features like IntelliSense can help out a lot but still, this can become challenging as the codebase grows. Changing the directory structure of the project leads to a change in all occurrences of the modules which are being referenced multiple times throughout the project. The project maintenance job is high, error-prone, confusing, and tiring.
Below is a sample of the relative path which needs to be imported every time when we need to use a module.
Relative path sample:
And that’s the reason for using path alias.
Aliases represent file paths or URLs to avoid typing the whole absolute paths or URLs. Path aliases make everything simple and compact which results in less typing, a better understanding of the directory structure, easy maintenance, and fewer errors. There are different ways of achieving this; ranging from configuring webpack resolve (React), using module-alias, or configuring the baseUrl and paths in the tsconfig file in case of TypeScript.
To register an alias module-alias modifies the internal Module._resolveFilename method so that when we import any module it matches the name with one of the registered aliases first, and if it matches then the already existing module is suggested and imported. module-alias modifies the internal Module._nodeModulePaths so that the current directory behaves as the node_modules directory.
Steps to follow:
Create aliases of directories and register custom module paths in NodeJS using module-alias.
Let’s first install module-alias
npm install module-alias
After installation, add the following code to your package.json file and configure it however you want.
Note: Remove all the comments in the json file to prevent lint-errors.
Your json file will look somewhat like below:
After that, add this line at the very top of the main file (index.js) of your app, before any code.
The above piece of code registers your aliases. If you have IntelliSense in our IDE, it will get auto-suggested.
Finally, you can see the change.
In the below image you should be able to see the module aliases suggested by the Intellisense in the VS Code (@sendgrid/mail is an example of the expected result)