Introduction
今天在做一个 Angular 项目的时候,遇到了一个问题:
1 | ERROR in src/app/app.module.ts:1:1 - error TS6059: File 'xxx' is not under 'rootDir' 'yyy'. 'rootDir' is expected to contain all source files. |
可以看到这个错误是关于rootDir
的,那么rootDir
是什么呢?看一下官网的解释:
Default: The longest common path of all non-declaration input files. If composite is set, the default is instead the directory containing the tsconfig.json file.
When TypeScript compiles files, it keeps the same directory structure in the output directory as exists in the input directory.
For example, let’s say you have some input files:
1 | MyProj |
The inferred value for rootDir is the longest common path of all non-declaration input files, which in this case is core/.
If your outDir was dist, TypeScript would write this tree:
1 | MyProj |
Importantly, rootDir does not affect which files become part of the compilation. It has no interaction with the include, exclude, or files tsconfig.json settings.
Note that TypeScript will never write an output file to a directory outside of outDir, and will never skip emitting a file. For this reason, rootDir also enforces that all files which need to be emitted are underneath the rootDir path.
重点看这句:rootDir also enforces that all files which need to be emitted are underneath the rootDir path.
也就是说,所有需要被编译的文件都必须在rootDir
的路径下,否则就会报错。
For example, let’s say you had this tree: 如果我们在tsconfig.json
中指定了rootDir
为core
,那么helpers.ts
就不在rootDir
的路径下,所以会报错。
1 | MyProj |
Nx based mono-repos.
如果是基于Nx的但一代码仓库,有时候也会出现这个错误,原因是一个Publishable的lib引用了另一个Non-Publishable的lib,这时候就会报错。详情请看这里, 关于Nx buildable/publishable libraries, please see here