找不到模块 - 打字稿路径别名错误

RTW*_*RTW 2 typescript

在编译时,我收到无法修复的错误:/

index.ts:2:19 - error TS2307: Cannot find module '@shared'
Run Code Online (Sandbox Code Playgroud)

任何想法为什么会这样?

项目结构:

在此处输入图片说明

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "../../build/backend",
  },
  "extends": "../../configs/tsconfig.base.json",
  "references": [
    {
      "path": "../shared"
    }
  ],
  "paths": {
    "@shared": [
      "../shared/index"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

后端/index.ts:

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

console.log(x)
Run Code Online (Sandbox Code Playgroud)

共享/index.ts:

export const x = 'this is shared index'
Run Code Online (Sandbox Code Playgroud)

小智 8

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

  • 不好意思说我也有同样的问题哈哈 感谢您发布此信息,让我意识到我做错了什么 (4认同)

RTW*_*RTW 6

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

tsc --traceResolution
Run Code Online (Sandbox Code Playgroud)

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

Resolving module name '@shared' relative to base url 'D:/apps/my-app/src' - 'D:/apps/my-app/src/@shared'.
Run Code Online (Sandbox Code Playgroud)

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

{
  "compilerOptions": {
    "moduleResolution": "node",
    "baseUrl": "../",
    "outDir": "../../build/backend"
  },
  "extends": "../../configs/tsconfig.base.json",
  "references": [
    {
      "path": "../shared"
    }
  ],
  "paths": { "shared": ["shared/index"] }
}
Run Code Online (Sandbox Code Playgroud)