网站搜索

Visual Studio Code - TypeScript 更倾向于导入相对路径而不是路径别名


有没有办法强制 TS 使用路径别名进行导入,如果有可用的路径别名?(我使用 VSCode)

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


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

Ts 配置提取

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

答案#1

我遇到了同样的问题,并按照这个 GitHub 问题解决了它 https://github.com/Microsoft/vscode/issues/59815

在 Visual Studio Code 内,通过输入 Ctrl + ,(Windows/Linux)或 CMD + ,(Mac)进入 设置,然后使用搜索设置框搜索 importModuleSpecifier,再从 TypeScript 部分选择非相对。

答案#2

我在 VSCode 中遇到过这个问题。问题是我在 settings.json 中将 importModuleSpecifier 设置为相对路径。将其设置为默认值解决了我的问题。

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

相关文章