求VSCode下可调试导入本地TypeScript模块的父项目配置示例
可直接复用的TypeScript跨本地模块调试配置方案
1. 标准项目结构参考
your-workspace/ ├── parent-project/ # 父项目 │ ├── package.json │ ├── tsconfig.json │ ├── src/ │ │ └── index.ts │ └── .vscode/ │ └── launch.json └── local-ts-module/ # 被导入的本地TypeScript模块 ├── package.json ├── tsconfig.json └── src/ └── index.ts
2. 本地TS模块配置
模块tsconfig.json配置
local-ts-module/tsconfig.json必须开启sourceMap生成调试映射:
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "Node", "outDir": "./dist", "rootDir": "./src", "sourceMap": true, // 必开,用于关联编译后代码和TS源码 "declaration": true, "strict": true, "esModuleInterop": true }, "include": ["src/**/*"] }
模块package.json配置
指定正确的入口和类型文件路径:
{ "name": "local-ts-module", "version": "1.0.0", "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "build": "tsc" } }
配置完成后执行一次npm run build生成dist目录文件。
3. 父项目配置
引入本地依赖
父项目package.json中通过相对路径引入本地模块:
{ "dependencies": { "local-ts-module": "../local-ts-module" } }
执行npm install完成依赖安装。
父项目tsconfig.json配置
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "Node", "outDir": "./dist", "rootDir": "./src", "sourceMap": true, // 必开 "sourceRoot": "./src", "inlineSources": true, // 可选,将源码嵌入映射文件提升调试稳定性 "strict": true, "esModuleInterop": true }, "include": ["src/**/*"], "references": [ // 可选,使用TS项目引用自动关联模块配置 { "path": "../local-ts-module" } ] }
4. VSCode调试核心配置(launch.json)
parent-project/.vscode/launch.json配置如下,重点是要将本地模块纳入sourcemap解析范围:
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "调试父项目+本地模块", "program": "${workspaceFolder}/src/index.ts", "preLaunchTask": "tsc: build - tsconfig.json", "outFiles": [ "${workspaceFolder}/dist/**/*.js", "${workspaceFolder}/../local-ts-module/dist/**/*.js" // 关联本地模块编译文件 ], "resolveSourceMapLocations": [ "${workspaceFolder}/**", "${workspaceFolder}/../local-ts-module/**", // 允许解析本地模块的sourcemap "!**/node_modules/**" // 排除第三方包映射避免冲突 ], "sourceMaps": true, "smartStep": true, "skipFiles": ["<node_internals>/**"] } ] }
5. 可选:ts-node免编译调试配置
如果不想每次修改代码都手动编译,可以用ts-node直接运行,调整launch.json配置即可:
{ "type": "node", "request": "launch", "name": "ts-node免编译调试", "program": "${workspaceFolder}/src/index.ts", "runtimeArgs": ["-r", "ts-node/register"], "cwd": "${workspaceFolder}", "sourceMaps": true, "resolveSourceMapLocations": [ "${workspaceFolder}/**", "${workspaceFolder}/../local-ts-module/**", "!**/node_modules/**" ], "skipFiles": ["<node_internals>/**"] }
父项目安装ts-node、typescript为开发依赖即可使用,无需提前编译父项目和本地模块代码。
验证方式
- 在本地模块的src目录TS文件中设置断点
- 父项目VSCode窗口按F5启动调试,即可直接命中断点,单步调试会直接跳转TS源码,不会进入编译后的JS文件
内容的提问来源于stack exchange,提问作者Warrick FitzGerald
相关产品推荐
相关产品推荐

