Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript paths not resolving

Here's the Github MCVE showing an issue. npm run compile shows the error.

I'm trying to do this:

import {Todo} from '@test';

But it's not resolving.

src/index.ts:1:20 - error TS2307: Cannot find module '@test'.

I have paths in tsconfig.json.

  "baseUrl": "./",                          /* Base directory to resolve non-absolute module names. */
  "paths": {
    "@fs/": ["src/"], 
    "@test/": ["test/"]
  },                                        /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */

Thoughts?

Github Typescript Issue

I opened a bug report for this here since per some of the comments it should have worked.

Typescript note that I updated the github repository removing the glob patterns and slashes in @test.

like image 610
Ole Avatar asked Mar 27 '19 18:03

Ole


People also ask

Can't resolve the path with the extensions TSX D TS?

The error "Could not resolve the path with the extensions '. ts', '. tsx'" occurs when we incorrectly use the tsc command. To solve the error, make sure to only pass valid flags to tsc , e.g. tsc --project tsconfig.

How does TypeScript resolve modules?

How TypeScript resolves modules. TypeScript will mimic the Node. js run-time resolution strategy in order to locate definition files for modules at compile-time. To accomplish this, TypeScript overlays the TypeScript source file extensions ( .

How do you use absolute path in TypeScript?

To be able to use absolute paths in TypeScript we can set the baseUrl property in the tsconfig. json file. With this, we define src as our root directory (for module resolution).


2 Answers

Don't adjust the VS Code Import Module Specifier settings (as per some answers floating around). And don't remove the glob patterns. In fact add some more in:

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

Notice that the glob is in the key AND the value. This is hilariously hard to spot sometimes.

Where the target is a file, the glob should be omitted from key and value.

like image 162
Jai Avatar answered Oct 22 '22 03:10

Jai


Remove the glob patterns:

"paths": {
  "@test": "./test"
}

Your solution is weirdly supposed to work, but the docs use no globs and there have been some reported intellisense bugs when using globs.

like image 27
Nino Filiu Avatar answered Oct 22 '22 02:10

Nino Filiu