为什么执行tsc编译时生成的文件不在当前仓库且报TS6059错误
前置项目信息
- 项目为TypeScript编译测试工程tsc-example,仅安装
typescript@^4.1.3作为依赖,配置了npm run build执行tsc编译命令 - 核心配置与源码内容如下:
- tsconfig.json 配置
{ "compilerOptions": { "baseUrl": "./", "allowJs": true, "strict": true, "target": "es6", "module": "commonjs", "lib": ["dom", "es6", "es5", "es2017", "esnext.asynciterable"], "sourceMap": true, "moduleResolution": "node", "removeComments": true, "noImplicitThis": true, "noUnusedLocals": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "esModuleInterop": true, "noUnusedParameters": false, "paths": { "src/*": ["./src/*"] }, "declaration": true, "rootDir": "./", "outDir": "dist" }, "exclude": ["node_modules", "dist", "__tests__", "jest.config.js"], "include": [ "/src/*", "@types"] }
- src/index.ts 业务代码
type mystring = string; type TFunc = (x: mystring) => string; const func: TFunc = (str) => str + str; const get = () => func('hello'); export default get;
- package.json 配置
{ "name": "tsc-example", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "tsc" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "typescript": "^4.1.3" } }
实际异常表现
执行编译命令npm run build后,输出如下报错:
error TS6059: File '/src/config.ts' is not under 'rootDir' 'c:/projects/tsc-example'. 'rootDir' is expected to contain all source files. error TS6059: File '/src/hot.tsx' is not under 'rootDir' 'c:/projects/droplets/tsc-example'. 'rootDir' is expected to contain all source files. error TS6059: File '/src/index.tsx' is not under 'rootDir' 'c:/projects/droplets/tsc-example'. 'rootDir' is expected to contain all source files. Found 3 errors.
编译过程会生成不属于当前项目的输出文件,文件内容全部来自本地其他项目的源码,生成的异常文件清单:
- config.d.ts
- config.js
- config.js.map
- hot.d.ts
- hot.js
- hot.js.map
- index.d.ts
- index.js
- index.js.map
问题核心根因
问题完全来自tsconfig.json中include的路径写法错误:
原配置里的"/src/*"是 带前导斜杠的磁盘根目录绝对路径写法,在Windows环境下,TypeScript解析该路径时会直接定位到当前运行环境的磁盘根目录下的src文件夹,而非tsconfig.json所在项目根目录下的src文件夹。
当扫描到磁盘根目录下存在其他项目遗留的src目录(即报错中提到的c:/projects/droplets路径下的tsx文件)时,TypeScript会自动将这些跨项目的文件全部纳入编译范围。而配置中指定的rootDir为当前项目的根目录./,这些从磁盘根目录读取的外部文件不在rootDir的覆盖范围内,因此触发TS6059报错;同时因为开启了declaration(生成类型声明文件)和sourceMap(生成源码映射文件)配置,TypeScript会尝试为这些外部项目的文件生成对应的编译产物,最终出现编译当前项目却生成其他项目文件的异常现象。
补充说明:如果路径写法为
"src/*"(不带前导斜杠),TypeScript会以tsconfig.json所在的项目根目录为基准定位相对路径,不会出现跨磁盘扫描的问题。
修复方式
将tsconfig.json中include的路径修改为无前置斜杠的相对路径即可:
把原有配置
"include": [ "/src/*", "@types"]
替换为
"include": [ "src/*", "@types"]
修改完成后重新执行npm run build,TypeScript将仅扫描当前项目范围内的源码文件,不会再触发跨项目文件的编译逻辑。
内容的提问来源于stack exchange,提问作者Inspiraller

