Use Module Path Import instead of Relative Path Import for typescript projects
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.
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.
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.
What to do
- Update the
tsconfig.jsonwith 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.jsonfor development and production:
The command below helps the ts-node to understand the module import:
ts-node -r tsconfig-paths/register src/index.ts
node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/index.js
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.