How to have path alias in Node.js ?
Last Updated :
18 May, 2021
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
Similar Reads
How to Get URL pathname in Next.js? Next.js is a powerful React framework that simplifies the process of building server-rendered and statically generated web applications. One common requirement in web development is to get the URL pathname, which can be useful for various purposes such as conditional rendering, routing, and analytic
3 min read
How to Setup View Engine in Node.js ? View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with
2 min read
How to Install Express in a Node Project? ExpressJS is a popular, lightweight web framework for NodeJS that simplifies the process of building web applications and APIs. It provides a robust set of features for creating server-side applications, including routing, middleware support, and easy integration with databases and other services.Be
2 min read
How to filter path of routes in Express.js ? Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will be discussing how to filter the paths of routes using the express.js in node.js. The ap
2 min read
How to Dynamically Call Router Function in Node.js ? In Node.js Dynamically calling a router function means that the function is selected at runtime based on the request parameters, instead of being explicitly defined in the code. This can be useful when you want to handle a large number of similar requests without having to define a separate function
4 min read