Top 10 Wholesale Marketplaces in The World
Discover top 10 wholesale marketplaces for eCommerce success, each offering unique advantages and niche specialties
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
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:
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
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
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.
Need help? Let us help you!
Get a detailed breakdown with cost & time estimations for any of your idea or project in 4 hours
We build user - centric software products that helps businesses grow at massive scale. Let's build together!
Contact usCheck out our carefully curated packages to build a high-quality product and get unparalleled support. Click on the button and find your match.
Explore our store