How to set up and use path aliases in NodeJS, ReactJS with Typescript

Grorapid Labs Mar 1, 2022

Recently, In one of my projects, I was having a hard time writing long import statements and it was something that was getting very annoying for me. If you also came across this problem and looking for a way to get around this then you jumped into the right place.

Problem: Using long import statements kind of sucks and the problem gets bigger when deeper the project trees grow.

Solution: Using path/module alias.

So before jumping into setup, let's understand what do we mean by path aliases

What are path/module aliases?

Path aliases are preconfigured names to replace long paths in code files and directories, with path aliases you can declare alias that will directly map to absolute paths in the code directory.

Here's a quick example

Before using path aliases:

After using path aliases:

Step 1:  Configure tsconfig.json

Go to tsconfig.json file and add baseUrl and paths variables which specify Typescript transpiler to resolve modules.

baseUrl: Source code directory which specified where to find modules for import statements.

paths: Specified how to resolve specific module names which are relative to baseUrl

Step 2: Configure NodeJS runtime to handle path aliases.

However, when you try to compile the Typescript code into Javascript and as soon as you run the code you will get an error something like

Error: Cannot find module  @service/handler...

That's because JS runtime can't resolve path modules and tsconfig is only applicable for the Typescript compiler.

So to resolve this issue we can use the npm module-alias package to create aliases and register paths in compiled Javascript code.

Next, install the npm module-alias package

Configure changes to package.json for registering path aliases. Note that dist is the folder where the compiled JS code resides.

Now the last step is to register the module and path aliases in code and you can do that by using the following line

That's it, now you can easily use path aliases in your project, no need to use ../../ import statements.

Feel free to leave comments!!

If you are interested in working with Grorapid labs for any technology based product or solution, feel free to reach out at [email protected]