There is a way to add alias to your node.js project :
You need to do three things. Add a jsconfig.json file at te root of your project, add _moduleAliases option and the module-alias lib inside your package.json and finally import the lib at the very top of your index.js.
1. Library installation
Run the following command to install the lib :
npm i --save module-alias
2. Jsconfig.json
Add a jsconfig.json will help your IDE to detect that you are using aliases. Here is an example of jsconfig.json file :
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"common/*"
],
"@routes/*": [
"common/routes/*"
],
"@utils/*": [
"common/utils/*"
],
"@helper/*": [
"common/helper/*"
],
"@hooks/*": [
"common/hooks/*"
]
}
},
"include": [
"common/**/*"
]
}
3. package.json
It is here that the magic happened. In your package.json file add the following lines.
It is important to be synchronised with the jsconfig.json file in order to get fully working aliases. !
...
"_moduleAliases": {
"@": ".",
"@routes": "common/routes",
"@utils": "common/utils",
"@hooks": "common/hooks",
"@helper": "common/helper"
},
"depedencies": {
...
"module-alias": "^2.2.2" #Latest current version
...
},
...
4. Index.js
At the very top of your index.js file add the following code :
require('module-alias/register')
...
This normally should do the trick
If needed, see the documentation here :