Typescript 更喜欢导入相对导入而不是路径别名

问题描述 投票:0回答:4

有没有办法强制 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"]
        }
    }
}
typescript visual-studio-code import
4个回答
11
投票

我遇到了同样的问题,并在这个 github 问题之后修复了它 https://github.com/Microsoft/vscode/issues/59815

在 Visual Studio Code 中,通过键入

Ctrl + ,
(Windows/Linux) 或 CMD + , (Mac) 转到 Settings,然后使用搜索设置框,搜索 importModuleSpecifier,然后从 TypeScript 部分中选择非-亲戚。


6
投票

我在 VSCode 中遇到过这个问题。问题是我在 settings.json 中将

importModuleSpecifier
设置为相对值。将其设置为默认值解决了我的问题。

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

1
投票

我有完全相同的问题,我认为这个问题与此相关https://github.com/microsoft/TypeScript/issues/47053

对我来说,绝对重要,例如。无论我选择哪种设置,

@/components/
始终是第二个选项。

这里提到的解决方案https://stackoverflow.com/a/72029899对我来说也不起作用,而且我也不想改变我的

index.ts
导入/导出的任何内容。

似乎有帮助的是设置路径使用

./
而不是
@/
并在 VSCode 中使用
"typescript.preferences.importModuleSpecifier": "non-relative"
设置,但感觉很奇怪,因为它看起来像相对路径。


0
投票

对于

paths
对象中的配置,请尝试以下操作:

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

也许直接引用

index.ts
是不正确的,因为它不是路径,而是文件。通配符可能也很重要。

仅供参考:我引用的是 TSConfig Reference

© www.soinside.com 2019 - 2024. All rights reserved.