DEV Community

Cover image for Path alias in Node.js
Ritwik Rohitashwa
Ritwik Rohitashwa

Posted on • Originally published at ritwik.hashnode.dev

Path alias in Node.js

While doing import in node.js application, we see a lot of '../'
path. As the project grows vertically deep this path gets much duskier. This really looks awful especially when we are building a production-grade big application.

import { AuthControlller } from '../../../user/userControlller'
import { your_module } from '../../../main/your_module'
Enter fullscreen mode Exit fullscreen mode

You can observe the path combination made of dots and backslashes ('../../../'). Obviously, this is not looking good in a project. As well in big projects, understanding the perfect location also gets duskier when we are assigning this to a new member of our team.

The Solution

We can use path alias to solve this problem and our code beautified.

What is a path alias?

It is a way to map paths into certain absolute paths which can be used in every corner of our application

Setup

Step 1. Install module-alias package

npm install --save module-alias
Enter fullscreen mode Exit fullscreen mode

Step 2. Update package.json

here we have to add our custom configuration into the package.json file so that this effect can be traced all around the project and with that, we can directly call this configuration just by importing it into the project files.

"_moduleAliases": {
    "@auth": "src/api/components/user/auth",
    "@your_module": "abc/cde/efg/hij/your_module"
}
Enter fullscreen mode Exit fullscreen mode

This abc/cde/efg/ is the path of your module main folder and @your_module is the name that you will use to import the module. Basically, it means that we are assigning the path to this @your_module

Note this **@ ** must be included before a module name.

Step 3. Update your files

Just use regular import statement with assigning to this path aliases

const your_module_name = require('@your_module')

ES6
import your_module from '@your_module'

modules with different files
import { authController } from '@auth/controllers'
Enter fullscreen mode Exit fullscreen mode

Additional steps for TypeScript

Step 4. Update tsconfig.json

"baseUrl": "./src"   // if your directory starts from src folder
"path": {
    "@your_module": ["src/api/components"]  // your module path
}
Enter fullscreen mode Exit fullscreen mode

Step 5. update index.ts or your main server file

Add this line on top of your main server file

// it imports the file all around the project 
import "module_alias/register"
Enter fullscreen mode Exit fullscreen mode

It's all done. Now let's go and execute our path alias and make our project beautified.

If you like this article then try it in your project. Also try to share this project to others.

Top comments (0)