TypeScript同文件多输出:如何确保共享函数编译到dist目录?
问题分析
核心原因是主tsconfig.json中的references配置,导致TypeScript将src/helpers/shared-functions视为独立子项目,跳过了主项目对该目录源码的编译——项目引用机制下,主项目会依赖子项目的编译产物,而非自行编译子项目源码。
解决方案
方法一:移除主tsconfig的项目引用(推荐)
直接删除主tsconfig.json中的"references"字段,因为你需要的是将同一源码编译到两个不同目录,而非依赖子项目产物:
// 主tsconfig.json(修改后) { "compilerOptions": { "target": "es2019", "module": "commonjs", "allowJs": true, "resolveJsonModule": true, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "rootDir": "src", "strict": true, "noImplicitAny": false, "strictNullChecks": false, "esModuleInterop": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["public", "node_modules", "dist"] }
修改后,主tsconfig的include: ["src/**/*"]会覆盖所有src下的文件,src/helpers/shared-functions会被正常编译到dist/helpers/shared-functions目录。
方法二:保留项目引用,通过脚本双编译
如果必须保留项目引用(比如子项目有独立依赖),可以通过单独执行两次编译命令实现双输出:
- 在
package.json中添加编译脚本:
"scripts": { "build:dist": "tsc -p tsconfig.json", "build:public": "tsc -p src/helpers/shared-functions/tsconfig.json", "build": "npm run build:dist && npm run build:public" }
- 调整主tsconfig,明确将子项目目录加入
include:
// 主tsconfig.json(调整后) { "compilerOptions": { // 原有编译选项保持不变 }, "include": ["src/**/*", "src/helpers/shared-functions/**/*"], "exclude": ["public", "node_modules", "dist"], "references": [{ "path": "src/helpers/shared-functions" }] }
这种方式可能存在重复编译风险,因此更推荐方法一。
验证结果
执行编译命令后,检查两个目标目录:
dist/helpers/shared-functions是否生成CommonJS规范的编译文件public/shared-functions是否生成ES6规范的编译文件
内容的提问来源于stack exchange,提问作者Michael Sanford
相关产品推荐
相关产品推荐

