0

I'm trying to get path resolution to work in typescript.

My folder structure so far looks like this:

  • src:
    • index.ts
    • types:
      • global.d.ts
      • cache.d.ts
    • util:
      • index.ts
      • Cache.ts

Since It's getting pretty nested I would like to be able to access for example the util folder by typing import { Whatever } from '@util'. I've tried setting baseUrl to ./src and paths to "@util": ["util/index"] with moduleResolution set to node.

This is how my files look so far:

src/index.ts

import {Cache} from '@util'

const c = new Cache();

src/util/index.ts

export { default as Cache } from './Cache';

src/util/Cache.ts

export default class {
// class code goes here
}

Now, the compiler doesn't complain while I'm coding in VS Code but when I run tsc in the command line I get an error saying that it can't find the module '@util'.

Does anyone have any ideas as to why I can't compile?

Will
  • 413
  • 6
  • 23
voiys
  • 269
  • 5
  • 14

2 Answers2

3

Okay, in the end I managed to solve it by using tsconfig-paths.

Because I wasn't using a bundler like webpack my custom paths weren't getting compiled along with the rest of the code. So instead of having resolved paths to the modules there would just a string looking like the path from the original source (import {Whatever} from '@util' instad of /absolute/path/to/@util/index).

You use tsconfig-paths by preloading it's register script when you call node/ts-node from the command line with the -r option (for example node -r tsconfig-paths/register dist/index.js). This converts the paths accordingly after emit.

voiys
  • 269
  • 5
  • 14
-1

what you are trying to import is a namespaced NPM package here while what you actually want to do is do a relative or absolute import i.e.:

import {Cache} from './util'

const c = new Cache();

For better understanding of the '@' import check this post

MarcinL
  • 130
  • 1
  • 6
  • thanks for the answer however I don't want to import them by using a relative/absolute import, I want to make the `paths` field from `tsconfig.json` work so I can import them without thinking about where the modules are located. It doesn't have to be called `@module` it can be just `module`, i.e. `util` – voiys Feb 20 '20 at 14:04
  • than they need to be NPM dependencies whatever you define in tsconfig JSON is then resolved using relative/absolute imports – MarcinL Feb 20 '20 at 14:31
  • I made a repl (https://repl.it/repls/LostPassionateSet) to show my files + tsconfig. I think I'm doing it right and it should work but It just doesn't – voiys Feb 20 '20 at 14:43
  • https://stackoverflow.com/questions/43281741/how-to-use-paths-in-tsconfig-json – MarcinL Feb 20 '20 at 15:42