导致错误导入的打字稿路径

时间:2021-01-29 18:27:26

标签: typescript

我正在使用 Typescript (4.1.3) 并且我开始在 tsconfig.json 中使用自定义路径。从那以后,当我导入任何 .ts 文件时,如果我不使用整个路径,就会出现错误:

<块引用>

错误:(138, 33) TS2307:找不到模块“pages/foo/bar”或其相应的类型声明。

为了解决这个问题,我必须添加前缀“src/”,所以我得到“src/pages/foo/bar”。项目本身运行良好,即使有这个 TS 错误。

这是我的 tsconfig.json 文件

{
"compilerOptions": {
    "allowJs": true,
    "sourceMap": true,
    "target": "es6",
    "strict": true,
    "declaration": false,
    "noImplicitAny": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strictNullChecks": false,
    "baseUrl": ".",
    "paths": {
        "foo": [
            "bar.js"
        ]
    },
    "types": [
        "quasar",
        "node",
        "cypress"
    ],
    "lib": [
        "es2018",
        "dom"
    ]
},
"exclude": [
    "node_modules"
],
"extends": "@quasar/app/tsconfig-preset"

}

2 个答案:

答案 0 :(得分:1)

这似乎是您的配置 baseUrl:"." 的问题,这意味着 js 模块解析发生在当前目录中,这就是为什么您的导入投诉要添加 src 目录。

确保将此配置指向 src 目录,然后所有导入解析都从该目录进行。示例:baseUrl:"./src"

更多详情:https://www.typescriptlang.org/tsconfig#baseUrl

答案 1 :(得分:1)

compilerOptions.baseUrl 被添加到 import 语句中指定的路径的前缀,以创建路径 relativetsconfig.json 文件的位置。

在您的情况下,与 tsconfig.json 文件相关的模块 bar.js 的路径是 src/pages/foo/bar。因此,您可以在 ./src 中指定 compilerOptions.baseUrl 或在 import 语句中指定完整路径。