错误 TS6059:文件不在 'rootDir' 下 .. 'rootDir' 应包含所有源文件

error TS6059: File is not under 'rootDir' .. 'rootDir' is expected to contain all source files

我收到这个相当荒谬的 tsc 转译错误:

error TS6059: File '/Users/alex/codes/interos/teros-cli/src/logging.ts' is not under 'rootDir' '/Users/alex/codes/teros/notifier-server/src'. 'rootDir' is expected to contain all source files.

我的 PWD 是 /Users/alex/codes/teros/notifier-server/Users/alex/codes/teros/notifier-server/tsconfig.json 的 tsconfig.json 文件是:

{
  "compilerOptions": {
    "outDir": "dist",
    "allowJs": false,
    "pretty": true,
    "resolveJsonModule": true,
    "sourceMap": false,
    "skipLibCheck": true,
    "rootDir": "src",
    "declaration": false,
    "baseUrl": ".",
    "target": "es2018",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "allowUnreachableCode": true,
    "lib": [
      "es2017",
      "es2018"
    ]
  },
  "compileOnSave": false,
  "include": [
    "src"
  ]
}

这似乎是一个错误..因为 teros-cli 目录在 PWD 之外, 由单独的 tsconfig.json 文件管理。

我什至将此字段更改为:

  "include": [
    "/Users/alex/codes/teros/notifier-server/src"
  ],
  "exclude": [
    "/Users/alex/codes/teros/teros-cli"
  ]

仍然得到同样的错误。

什么是 rootDir

rootDir is set to a root folder, that contains all your source files. If not specified, TS will automatically choose a suitable parent folder of all inputs. rootDir also .

错误是什么意思?

我猜你在 notifier-server:

的某个地方有 logging.tsimport 语句
import {logger} from "@teros-cli/logging" // or similar

然后 logging.ts 模块将被编译器 automatically included,而不考虑 tsconfig.json 中的 includeexclude 选项。检查所有包含文件的一种方法是 tsc --listFiles.

notifier-server 之外的 tsconfig.json 文件在这里没有帮助。编译器每次 tsc 编译只选择一个配置,并可选择拉取 inherited configs. If it cannot find one in notifier-server project root (where you started tsc), only then the compiler searches upwards the parent directory chain,直到找到配置。

可能的解决方案

一个修复方法是从编译器选项中删除 "rootDir": "src",这样它就会自动设置。注意:rootDir 会将这两个项目都视为输入!

备选方案:您可以添加包含在 notifier-server/src 项目中的单独 logging.ts 模块并删除外部 import.

希望对您有所帮助!

在我的例子中,原因是循环依赖。例如:

// Page.ts
import { Grid } from "./components/Grid";
export const test = "";

// Grid.ts
import { test } from "../Page"; // circular dep!