ByteNoteByteNote

字节笔记本

2026年2月19日

使用 ts-node 和 VS Code 调试 TypeScript 代码

API中转
¥120

本文介绍如何使用 ts-node 和 VS Code 调试 TypeScript 代码,无需等待编译即可直接运行和调试 TS 文件。

传统方案的问题

在使用 VS Code + Gulp 自动编译 TypeScript 的传统方案中,开发者常遇到以下问题:

  1. 编译等待时间:运行或调试需要等待编译完成,项目大了之后编译这一步还是需要一定的时间
  2. 测试代码难以调试:测试代码的调试配置较为复杂

ts-node 解决方案

ts-node 提供了 TypeScript 的运行环境,让我们免去了麻烦的编译这一步骤。

基础用法

javascript
require('ts-node').register();
require('./ts-code'); // 直接加载运行 ts 文件

通过 ts-node,可以直接在 Node.js 环境中运行 TypeScript 代码,无需预编译。

配置步骤

1. 安装依赖

bash
npm install --save-dev ts-node typescript

2. 配置 tsconfig.json

需要开启 sourceMap 以支持调试:

json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

3. 配置 VS Code 调试

创建 .vscode/launch.json 文件:

调试当前 TS 文件

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Current TS File",
      "type": "node",
      "request": "launch",
      "args": ["${relativeFile}"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector",
      "console": "integratedTerminal"
    }
  ]
}

配置说明:

  • --nolazy:禁用延迟加载,确保断点生效
  • -r ts-node/register:注册 ts-node,使 Node.js 可以运行 TS 文件
  • sourceMaps:启用源码映射,支持在 TS 文件中打断点
  • protocol: inspector:使用 Chrome DevTools 协议

调试 Mocha 测试

json
{
  "name": "Debug Current TS Tests File",
  "type": "node",
  "request": "launch",
  "program": "${workspaceRoot}/node_modules/.bin/_mocha",
  "args": [
    "-r", "ts-node/register",
    "${relativeFile}",
    "--colors",
    "-t", "100000"
  ],
  "sourceMaps": true,
  "cwd": "${workspaceRoot}",
  "protocol": "inspector",
  "console": "integratedTerminal"
}

4. 运行所有测试

package.json 中配置测试脚本:

json
{
  "scripts": {
    "test": "mocha -r ts-node/register src/**/*.spec.ts --colors",
    "test:watch": "mocha -r ts-node/register src/**/*.spec.ts --colors --watch"
  }
}

运行测试:

bash
npm test

VS Code 调试快捷键

快捷键功能
F5开始调试 / 继续执行
Cmd/Ctrl + Shift + F5重启调试
Shift + F5结束调试
F9添加 / 移除断点
F10单步跳过(Step Over)
F11单步调试(Step Into)
Shift + F11单步跳出(Step Out)

完整 launch.json 示例

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Current TS File",
      "type": "node",
      "request": "launch",
      "args": ["${relativeFile}"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector",
      "console": "integratedTerminal"
    },
    {
      "name": "Debug Current TS Tests File",
      "type": "node",
      "request": "launch",
      "program": "${workspaceRoot}/node_modules/.bin/_mocha",
      "args": [
        "-r", "ts-node/register",
        "${relativeFile}",
        "--colors",
        "-t", "100000"
      ],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector",
      "console": "integratedTerminal"
    },
    {
      "name": "Debug All Tests",
      "type": "node",
      "request": "launch",
      "program": "${workspaceRoot}/node_modules/.bin/_mocha",
      "args": [
        "-r", "ts-node/register",
        "src/**/*.spec.ts",
        "--colors",
        "-t", "100000"
      ],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector",
      "console": "integratedTerminal"
    }
  ]
}

示例代码

src/index.ts

typescript
import { add, multiply } from './math';

const result1 = add(2, 3);
console.log('2 + 3 =', result1);

const result2 = multiply(4, 5);
console.log('4 * 5 =', result2);

src/math.ts

typescript
export function add(a: number, b: number): number {
  return a + b;
}

export function multiply(a: number, b: number): number {
  return a * b;
}

src/math.spec.ts

typescript
import { expect } from 'chai';
import { add, multiply } from './math';

describe('Math functions', () => {
  it('should add two numbers', () => {
    expect(add(2, 3)).to.equal(5);
  });

  it('should multiply two numbers', () => {
    expect(multiply(4, 5)).to.equal(20);
  });
});

示例项目

作者提供了完整的 demo 项目供参考:

GitHub: https://github.com/MinionsDave/ts-node-demo

常见问题

断点不生效

确保 tsconfig.json 中开启了 sourceMap: true,并且 launch.json 中设置了 sourceMaps: true

模块导入错误

如果使用了 ES6 模块语法,确保 tsconfig.json 中配置了:

json
{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true
  }
}

路径别名问题

如果使用了路径别名(如 @/utils),需要额外配置:

bash
npm install --save-dev tsconfig-paths

然后在 launch.json 中添加:

json
"runtimeArgs": [
  "--nolazy",
  "-r", "ts-node/register",
  "-r", "tsconfig-paths/register"
]

总结

使用 ts-node + VS Code 调试 TypeScript 的优势:

  • 无需编译:直接运行 TS 文件,省去编译等待时间
  • 调试友好:支持断点、单步调试、变量查看
  • 测试支持:轻松调试 Mocha/Jest 测试代码
  • 配置简单:只需简单的 launch.json 配置

对于需要频繁调试 TypeScript 代码的开发者来说,这是一个高效的开发方案。

分享: