【问题标题】:Cannot find module - typescript path alias error找不到模块 - 打字稿路径别名错误
【发布时间】:2022-01-03 15:09:43
【问题描述】:

编译时出现无法修复的错误:/

index.ts:2:19 - error TS2307: Cannot find module '@shared'

有什么想法吗?

项目结构:

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "../../build/backend",
  },
  "extends": "../../configs/tsconfig.base.json",
  "references": [
    {
      "path": "../shared"
    }
  ],
  "paths": {
    "@shared": [
      "../shared/index"
    ]
  }
}

后端/index.ts:

import 'module-alias/register'
import { x } from '@shared'

console.log(x)

共享/index.ts:

export const x = 'this is shared index'

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用此命令来跟踪问题:

    tsc --traceResolution
    

    我发现“@shared”被用作文件夹名称,所以它看起来像:

    Resolving module name '@shared' relative to base url 'D:/apps/my-app/src' - 'D:/apps/my-app/src/@shared'.
    

    在我将别名更改为“共享”并设置 baseUrl 后,一切都开始工作了:

    {
      "compilerOptions": {
        "moduleResolution": "node",
        "baseUrl": "../",
        "outDir": "../../build/backend"
      },
      "extends": "../../configs/tsconfig.base.json",
      "references": [
        {
          "path": "../shared"
        }
      ],
      "paths": { "shared": ["shared/index"] }
    }
    

    【讨论】:

    【解决方案2】:

    天哪,我终于弄明白了。 baseUrl 和路径应该在 compilerOptions 内部而不是外部!

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2021-06-28
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 2014-11-21
      相关资源
      最近更新 更多