DEV Community

Cover image for How I simplified my import paths in TypeScript

How I simplified my import paths in TypeScript

Andy Coupe on July 17, 2020

I think as developers using ES modules we have all got to a point where import paths start to become ugly and unmaintainable - especially in large ...
Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Just a note about monorepos, look at tsc -b package1/tsconfig.json package2/tsconfig.json its helpful.

Collapse
 
cyberhck profile image
Nishchal Gautam

IDEs might get confused with this, if you're using an editor worth its salt, it should be able to do auto imports anyway.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

It's needed for the Typescript compiler to understand packages that sit in sibling arrangements that are not resolvable in node style resolution. I use webstorm which is salty haha.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Actually, it is resolved in VSCode, because it is also Microsoft's product.

Collapse
 
ryands17 profile image
Ryan Dsouza

But wouldn't Node complain after we transpile TS, as Node doesn't know about absolute paths?

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

tsc will automatically resolve it.

ts-node and ts-node-dev currently won't, but can be fixed with -r tsconfig-paths/register.

Collapse
 
ryands17 profile image
Ryan Dsouza

Doesn't work. Created a simple example with absolute imports and then compiled it via tsc. On running node dist/index.js the compiled JS throws an error as the absolute paths are not resolved.

Thread Thread
 
andrewmcoupe profile image
Andy Coupe

Let's see your example buddy?

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

It can be fixed via babel-plugin-module-resolver, though. Actually, Babel can do much more than tsc, and typescript can run under it as well.

Only just it doesn't help with the IDE.

Thread Thread
 
ryands17 profile image
Ryan Dsouza

I have two files:

src/index.ts

import { add } from 'utils/math'

console.log(add(2, 3))

src/utils/math.ts

export const add = (a, b) => a + b

My tsconfig.json - the rest is omitted

{
  "baseUrl": "./src",
  "paths": {
     "*": ["*"]
  }
}

After transpiling this to JS, it doesn't work just by calling node dist/index.js, where dist is the output folder. So the baseUrl is just for TypeScript as Node doesn't understand that.

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt

Now I really need to compile to JavaScript as you mentioned.

I summed up the solution, but not exactly that pretty.

Collapse
 
fullstackcoder profile image
fullstackcoder

That's a good one, I used it before. Although, personal feeling, the barrels (index.ts) is a better approach.

Collapse
 
andrewmcoupe profile image
Andy Coupe

You can use it with barrels 👍

Collapse
 
jonasgroendahl profile image
Jonas Grøndahl

Didn’t know about this, thanks!!