voiys
voiys

Reputation: 299

Typescript can't find module on compile

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

My folder structure so far looks like this:

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?

Upvotes: 0

Views: 3375

Answers (2)

voiys
voiys

Reputation: 299

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.

Upvotes: 3

MarcinL
MarcinL

Reputation: 130

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

Upvotes: -1

Related Questions