【问题标题】:Typescript path resulting in wrong import打字稿路径导致错误的导入
【发布时间】:2021-05-03 16:35:55
【问题描述】:

我正在使用 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"

}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    只需将“typescript-path-fix”添加到您的任务运行器管道中或在编译代码之前调用它

    使用此软件包解决您的问题: https://www.npmjs.com/package/typescript-path-fix

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我明白了,但是为什么只有在 tsconfig 中添加“路径”配置才会出现这种情况?
      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2021-06-28
        • 2022-11-05
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 2017-05-29
        • 2017-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多