Use Module Path Import instead of Relative Path Import for typescript projects
TypeScript best practices

This is a pretty straightforward tutorial on using module path import instead of relative path import in TypeScript. We’ll also cover getting rid of “../../../” on top of your files.
Problem
If you are a TypeScript or JavaScript developer, you have surely seen these dot slashes (“../../../”) on top of your files. When you import more than two or three components, it becomes a nightmare to figure out which components belong to which module at a glance.

There are some solutions, but each of them has cons and side effects to the project structure. For instance, using babel/typescript will result in you losing the *.d.ts files in the output. With webpack, setting up will take a lot of time.
Solution
TypeScript by default supports module import. Unlike with those ugly dot slashes, you can configure module paths in tsconfig.json
and then use them for import.


There is a problem with this: Compiling the TypeScript code to JavaScript makes it unusable by JavaScript. JavaScript does not understand those module paths. Also, tools like ts-node or ts-jest do not understand these module path imports.
There is an npm package (tsconfig-path) that resolves these module imports in runtime and helps JavaScript to run the compiled code. It helps ts-node and ts-jest to understand these components as well.
What to do
- Update the
tsconfig.json
with the correct path configuration. I use src/* as a single item, but you can use multiples.

- Install the tsconfig-path module:
npm install --save-dev tsconfig-paths
Note: Use this module to load modules whose locations are specified in the paths
section of tsconfig.json
. Both loading at runtime and via API are supported.
- Then simply add two scripts to
package.json
for development and production:

The command below helps the ts-node to understand the module import:
ts-node -r tsconfig-paths/register src/index.ts
And the command below helps Node/JavaScript understand the module import and be able to run the code:
node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/index.js
Conclusion
That’s it! All you needed to do was update your tsconfig.json
with the correct config, which includes paths, then install tsconfig-path and update your package.json
file with the correct scripts.