阿里云主机折上折
  • 微信号
Current Site:Index > Debugging configuration and techniques

Debugging configuration and techniques

Author:Chuan Chen 阅读数:3579人阅读 分类: TypeScript

Debugging Configuration and Techniques

The debugging experience in TypeScript directly impacts development efficiency. Proper configuration and techniques can quickly locate issues and reduce ineffective debugging time.

Basic Debugging Configuration

TypeScript projects typically require configuring compilation options in tsconfig.json to optimize the debugging experience:

{
  "compilerOptions": {
    "sourceMap": true,
    "inlineSources": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}

Key parameter explanations:

  • sourceMap: Generates .map files to link compiled code with source code
  • inlineSources: Embeds source code directly into the sourcemap file
  • strict: Enables all strict type checks (recommended to enable)

VSCode Debugging Setup

launch.json Configuration

{
  "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>/**"]
    }
  ]
}

Debugging Techniques

  1. Conditional Breakpoints: Right-click a breakpoint to set a condition expression
    // Trigger breakpoint when i > 5
    for (let i = 0; i < 10; i++) {
      console.log(i); // Set conditional breakpoint here: i > 5
    }
    
  2. Logpoints: Output logs without interrupting execution
    function calculate(a: number, b: number) {
      // Set logpoint here: `Calculation parameters: a=${a}, b=${b}`
      return a * b;
    }
    

Browser Environment Debugging

Webpack Configuration Essentials

// webpack.config.js
module.exports = {
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  }
};

Chrome Debugging Techniques

  1. Workspace Mapping: Map compiled code back to source code
  2. Blackbox Scripts: Ignore call stacks from third-party libraries
    // Example: Ignore lodash call stacks
    import _ from 'lodash';
    _.map([1,2,3], n => n*2); 
    

Advanced Debugging Scenarios

Asynchronous Code Debugging

async function fetchData() {
  // 1. Set breakpoints on await statements when using async/await
  const response = await fetch('/api/data');
  
  // 2. Debugging techniques for Promise chains
  return response.json()
    .then(data => {
      // Set breakpoint here
      return processData(data);
    })
    .catch(err => {
      debugger; // Automatic breakpoint
      throw err;
    });
}

Generic Type Debugging

interface Response<T> {
  data: T;
  status: number;
}

function parseResponse<T>(res: Response<T>) {
  // During debugging, hover to see the concrete type of T
  const result = res.data;
  return transform(result);
}

Performance Issue Debugging

Type Instantiation Depth Warnings

// When encountering "Type instantiation is excessively deep" errors
type DeepArray<T> = T extends any[] ? DeepArray<T[number]> : T;

// Solution: Add type constraints
type SafeDeepArray<T, Depth extends number> = 
  Depth extends 0 ? T :
  T extends any[] ? SafeDeepArray<T[number], Subtract<Depth, 1>> : T;

Memory Leak Detection

class Cache {
  private store = new Map<string, any>();

  // Detect cases where cache isn't cleared
  set(key: string, value: any) {
    this.store.set(key, value);
    // Record memory snapshots here during debugging
  }
}

Test Environment Debugging

Jest Configuration Example

// jest.config.js
module.exports = {
  preset: 'ts-jest',
  globals: {
    'ts-jest': {
      diagnostics: {
        warnOnly: true // Show type warnings during tests without interrupting
      }
    }
  }
};

Test Debugging Techniques

describe('API Test', () => {
  it('should handle errors correctly', () => {
    // 1. Start tests with --inspect-brk parameter
    // 2. Add debugger statements in test cases
    debugger;
    expect(() => fetchErrorApi()).toThrow();
  });
});

Production Issue Tracking

Sourcemap Upload Configuration

# Upload sourcemaps using source-map-tool
npx source-map-upload \
  --api-key=YOUR_KEY \
  --app-version=1.0.0 \
  --minified-url=*.js \
  --source-map-path=./dist

Error Stack Parsing

function parseError(stack: string) {
  // Use source-map library to parse production errors
  const rawStack = stack.split('\n');
  return rawStack.map(line => {
    // Parse minified line and column numbers
    return convertToOriginalPosition(line);
  });
}

Custom Tool Extensions

VSCode Debug Adapter

class TsDebugAdapter implements vscode.DebugAdapter {
  // Implement custom debugging protocol
  handleMessage(message: DebugProtocol.Message) {
    if (message.type === 'request' && message.command === 'evaluate') {
      // Handle expression evaluation requests
      this.sendResponse({
        type: 'response',
        request_seq: message.seq,
        success: true,
        body: {
          result: evaluateTSExpression(message.arguments.expression),
          variablesReference: 0
        }
      });
    }
  }
}

Chrome Extension Debugging

// background.ts
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  // Use chrome.debugger API to attach debugging sessions
  chrome.debugger.attach({ tabId: sender.tab?.id }, '1.0', () => {
    chrome.debugger.sendCommand(
      { tabId: sender.tab?.id },
      'Runtime.evaluate',
      { expression: 'debugger;' }
    );
  });
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:数据故事讲述

下一篇:代码迁移策略

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.