Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 30, 2021 06:12 am GMT

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'

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

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"}

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')ES6import your_module from '@your_module'modules with different filesimport { authController } from '@auth/controllers'

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}

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"

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.


Original Link: https://dev.to/ritwik2994/path-alias-in-node-js-4p6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To