使用ts-node和vsc来调试TypeScript代码

我以前写过一篇用vsc+gulp来自动编译ts并重启程序的文章,不事后来发现这样作的工做比较多并且有不少不足,好比node

  1. 运行或者调试须要等待编译完成,项目大了以后编译这一步仍是须要必定的时间的
  2. 难以调试测试代码,通常来讲项目采用ts,测试代码也应该采用ts去编写,而采用编译+sourcemap的方式就很难调试测试代码

TS-NODE

能够看出这些不足都来自于一个根本缘由,运行以前须要编译。后来我就发现了一个很强大的工具ts-node,来看下ts-node的简介:git

TypeScript execution environment and REPL for node.

简单的说就是它提供了TypeScript的运行环境,让咱们免去了麻烦的编译这一步骤。最简单的例子,在注册ts-node以后,咱们就能够直接加载并运行ts文件github

require('ts-node').register();

// 这样就能直接加载并运行 ./ts-code.ts...
require('./ts-code');

TS Config

为了断点调试,咱们须要在tsconfig.json中开启sourceMapnpm

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "noImplicitAny": true,
    "outDir": "./dist",
    "sourceMap": true
  },
  "include": [
    "src/**/*"
  ],
}

VSC Launch.json 配置

为ts-node注册一个vsc的debug任务,修改项目的launch.json文件,添加一个新的启动方式json

{
  "name": "Current TS File",
  "type": "node",
  "request": "launch",
  "args": [
    "${workspaceRoot}/src/index.ts" // 入口文件
  ],
  "runtimeArgs": [
    "--nolazy",
    "-r",
    "ts-node/register"
  ],
  "sourceMaps": true,
  "cwd": "${workspaceRoot}",
  "protocol": "inspector",
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen"
}

经过这些简单的配置,咱们在vsc的debug界面中选择Debug by ts-node的任务,就能够开始愉快的调试了,修改代码以后直接重启服务便可,这里简单的介绍一些vsc debug相关的快捷键,参考gulp

  1. F5 - 开始调试、继续执行
  2. cmd(ctrl) + shift + F5 - 重启
  3. shift + F5 - 结束调试
  4. F9 - 添加断点
  5. F10 - 单步跳过
  6. F11 - 单步调试
  7. shift + f11 - 单步跳出

调试当前打开ts文件

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

调试 mocha 测试代码

在launch.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" // 设置超时时间,由于调试时执行时间较长容易触发超时
  ],
  "cwd": "${workspaceRoot}",
  "protocol": "inspector"
}

而后打开一个包含mocha单元测试的ts文件,添加断点,运行Debug Current TS Tests File便可进行断点调试。
运行项目中的全部单元测试建议在package.json中添加test脚本,好比单元测试

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

而后运行npm test便可测试

例子

demo,这是我编写的一个很是简单的ts项目,包含了上述的全部配置,但愿对您有用。ui

相关文章
相关标签/搜索