Typescript 路径导致错误导入

Edu*_*usa 1 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"
Run Code Online (Sandbox Code Playgroud)

}

Ria*_*nli 5

compilerOptions.baseUrl以语句中指定的路径为前缀,import以创建对于文件位置的路径tsconfig.json

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

  • 无法使用 tsc 或 ts-loader。 (2认同)