Open In App

How to have path alias in Node.js ?

Last Updated : 18 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Javascript




import React, { component } from 'react';
const Module_Name = require('../../../../../../../../Module_Name');
import Icon from '../atoms/Typography';
import { userFetchRequest } from '../../../store/actions';


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.

 Approach:

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

Syntax:

npm install module-alias

Output:

expected result after installation

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.

Javascript




// Aliases
"_moduleAliases": {
  "@root"      : ".", // root directory
  "@deep"      : "src/some/deep/directory/or/file",
  "@my_module" : "lib/some-file.js",
  "something"  : "src/foo", // Or without @. It could be any string
}
   
// following is optional
// Custom module directories, same as 
//`node_modules` but with private modules
"_moduleDirectories": ["node_modules_custom"],


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.

Javascript




require('module-alias/register')


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.

Javascript




require('name_of_module_you_require')
const module = require('@root/some-module')
const veryDeepModule = require('@deep/my-module')
  
// module from `node_modules_custom` directory
 const customModule = require('my_private_module'
  
// Or ES6
import 'name_of_module_you_require'
import module from '@root/some-module'
import veryDeepModule from '@deep/my-module'
  
// Module from `node_modules_custom` directory
import customModule from 'my_private_module'


Final Output:

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)

Intellisense suggesting module alias



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads