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 hide API key in Node ?
When building applications that interact with third-party services or APIs, using API keys for authentication and authorization is common. However, exposing these keys in your codebase can pose significant security risks. Malicious actors could misuse your API keys, leading to unauthorized access, d
2 min read
How to Access Cache Data in Node.js ?
Caching is an essential technique in software development that helps improve application performance and scalability by temporarily storing frequently accessed data. In Node.js, caching can significantly reduce database load, minimize API response times, and optimize resource utilization. This artic
5 min read
How to Access the File System in Node.js ?
In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
3 min read
How to Copy a File in Node.js?
Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
2 min read
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 Catch All Routes in Next.js ?
To catch all routes in Next.js, you create a dynamic route file using the catch-all segments syntax. This allows you to handle various routes dynamically, enhancing routing flexibility and application structure.Catch all routesTo catch all routes in next js, We willCreate a file named [...gfg].js in
2 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 read and write files in Node JS ?
NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to generate short id in Node.js ?
In this article we are going to see how to generate a short id in Node.js. There is an NPM package called âshortidâ used to create short non-sequential url-friendly unique ids. By default, it uses 7-14 url-friendly characters: A-Z, a-z, 0-9, _-. It Supports cluster (automatically), custom seeds, cus
1 min read
How to Install NPM FS in Node JS ?
The file system module allows you to work with the file system on your computer NodeJS includes the fs module, to communicate with file systems. It provides functionality for interacting with the file system, such as reading from and writing to files, creating and removing directories, etc. The File
4 min read