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
tsconfig.json file and add
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.
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
Next, install the npm
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!!