简体   繁体   中英

Typescript prefers importing relative import instead of path alias

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"]
        }
    }
}

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"
}

I have exactly the same problem and I think this issue is related to this https://github.com/microsoft/TypeScript/issues/47053 .

For me, the absolute import, eg. @/components/ is always second option, no matter which setting I choose.

The solution mentioned here https://stackoverflow.com/a/72029899 did not work for me as well, and I also don't want to change anything about my index.ts import/exports.

What seems to help is to set paths to use ./ instead of @/ and use "typescript.preferences.importModuleSpecifier": "non-relative" setting in VSCode, but it feels really strange since it looks like a relative path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM