调试配置与技巧
调试配置与技巧
TypeScript 的调试体验直接影响开发效率。合理的配置与技巧能快速定位问题,减少无效调试时间。
基础调试配置
TypeScript 项目通常需要配置 tsconfig.json
中的编译选项来优化调试体验:
{
"compilerOptions": {
"sourceMap": true,
"inlineSources": true,
"outDir": "./dist",
"rootDir": "./src"
}
}
关键参数说明:
sourceMap
: 生成.map
文件关联编译后代码与源码inlineSources
: 将源码直接嵌入 sourcemap 文件strict
: 启用所有严格类型检查(推荐开启)
VSCode 调试方案
launch.json 配置
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Current TS File",
"program": "${file}",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"skipFiles": ["<node_internals>/**"]
}
]
}
调试技巧
- 条件断点:右键断点设置条件表达式
// 当i大于5时触发断点 for (let i = 0; i < 10; i++) { console.log(i); // 在此行设置条件断点:i > 5 }
- 日志点:不中断执行的日志输出
function calculate(a: number, b: number) { // 在此行设置日志点:`计算参数: a=${a}, b=${b}` return a * b; }
浏览器环境调试
webpack 配置要点
// webpack.config.js
module.exports = {
devtool: 'source-map',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};
Chrome 调试技巧
- Workspace 映射:将编译后代码映射回源码
- 黑盒脚本:忽略第三方库的调用栈
// 示例:忽略lodash的调用栈 import _ from 'lodash'; _.map([1,2,3], n => n*2);
高级调试场景
异步代码调试
async function fetchData() {
// 1. 使用async/await时可在await语句设断点
const response = await fetch('/api/data');
// 2. Promise链式调用调试技巧
return response.json()
.then(data => {
// 在此处设置断点
return processData(data);
})
.catch(err => {
debugger; // 自动断点
throw err;
});
}
泛型类型调试
interface Response<T> {
data: T;
status: number;
}
function parseResponse<T>(res: Response<T>) {
// 调试时可通过鼠标悬停查看T的具体类型
const result = res.data;
return transform(result);
}
性能问题调试
类型实例化深度警告
// 当出现Type instantiation is excessively deep错误时
type DeepArray<T> = T extends any[] ? DeepArray<T[number]> : T;
// 解决方案:增加类型约束
type SafeDeepArray<T, Depth extends number> =
Depth extends 0 ? T :
T extends any[] ? SafeDeepArray<T[number], Subtract<Depth, 1>> : T;
内存泄漏检测
class Cache {
private store = new Map<string, any>();
// 检测缓存未清理的情况
set(key: string, value: any) {
this.store.set(key, value);
// 调试时可在此处记录内存快照
}
}
测试环境调试
Jest 配置示例
// jest.config.js
module.exports = {
preset: 'ts-jest',
globals: {
'ts-jest': {
diagnostics: {
warnOnly: true // 测试时显示类型警告但不中断
}
}
}
};
测试调试技巧
describe('API测试', () => {
it('应正确处理错误', () => {
// 1. 使用--inspect-brk参数启动测试
// 2. 在测试用例中添加debugger语句
debugger;
expect(() => fetchErrorApi()).toThrow();
});
});
生产环境问题追踪
Sourcemap 上传配置
# 使用source-map-tool上传sourcemap
npx source-map-upload \
--api-key=YOUR_KEY \
--app-version=1.0.0 \
--minified-url=*.js \
--source-map-path=./dist
错误堆栈解析
function parseError(stack: string) {
// 使用source-map库解析生产环境错误
const rawStack = stack.split('\n');
return rawStack.map(line => {
// 解析压缩后的行列号
return convertToOriginalPosition(line);
});
}
自定义工具扩展
VSCode 调试适配器
class TsDebugAdapter implements vscode.DebugAdapter {
// 实现自定义调试协议
handleMessage(message: DebugProtocol.Message) {
if (message.type === 'request' && message.command === 'evaluate') {
// 处理表达式求值请求
this.sendResponse({
type: 'response',
request_seq: message.seq,
success: true,
body: {
result: evaluateTSExpression(message.arguments.expression),
variablesReference: 0
}
});
}
}
}
Chrome 扩展程序调试
// background.ts
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// 使用chrome.debugger API附加调试会话
chrome.debugger.attach({ tabId: sender.tab?.id }, '1.0', () => {
chrome.debugger.sendCommand(
{ tabId: sender.tab?.id },
'Runtime.evaluate',
{ expression: 'debugger;' }
);
});
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn