Typescript prefers importing relative import instead of path alias

Viewed 404

Is there a way to force TS to use a path alias for imports if there is one available? (I use VSCode)

import { ApiError } from '../../../../libs/shared/src'; // This is imported by default
//import { ApiError } from '@rita/shared'; // I want this


const err: ApiError = { /* ... */ };

Ts config extract

{
    "compilerOptions": {
        "rootDir": ".",
        "baseUrl": ".",
        "allowSyntheticDefaultImports": true,
        "target": "ES2017",
        "module": "esnext",
        "moduleResolution": "node",
        "forceConsistentCasingInFileNames": true,
        "importHelpers": true,
        "paths": {
            "@rita/helpers": ["libs/helpers/src/index.ts"],
            "@rita/maps": ["libs/maps/src/index.ts"],
            "@rita/rxjs": ["libs/rxjs/src/index.ts"],
            "@rita/shared": ["libs/shared/src/index.ts"]
        }
    }
}
2 Answers

For the config in paths object, try this:

{
  "@rita/helpers/*": ["libs/helpers/src/*"],
  "@rita/maps/*": ["libs/maps/src/*"],
  "@rita/rxjs/*": ["libs/rxjs/src/*"],
  "@rita/shared/*": ["libs/shared/src/*"]
}

Perhaps referencing the index.ts directly isn't right, as it's not a path, but a file. And the wildcard might be important too.

FYI: I'm referencing the TSConfig Reference.

I've had this issue in VSCode. The problem was I have set importModuleSpecifier to relative in settings.json. Setting this to default fixed my issue.

{
   // remove this or set to "shortest"
  "typescript.preferences.importModuleSpecifier": "relative"
}
Related