VSCode中使用断点调试typescript
nodejs服务器,使用typescript作为开发语言,苦于测试时频繁编译和重启。你还在为这种糟糕的测试过程烦恼么?试试这篇文章介绍的方案。
1.ts-node
npm地址:https://www.npmjs.com/package/ts-node
ts-node是一个很好用的工具,在npm上已经有四百多万的周下载数。它是一个支持在nodejs环境下直接运行typescript源代码的工具。
安装:
yarn add ts-node -d -s
这里演示为本地安装,本地安装和全局安装的区别是在调用cli命令时,本地安装需要加上管理工具的前缀,并且要在安装工具的项目目录下运行。
我们搭建一个简单的typescript脚本试验一下
我们在已经初始化好的express服务下新建ts脚本
./src/demo.ts
let word: string = "Test the power of ts-node";
function say(word: string): void {
console.log(word);
}
say(word);
然后使用ts-node运行命令
yarn ts-node/register./src/demo.ts
运行结果:
PS E:\projects\migao-node-service> yarn ts-node ./src/demo.ts
yarn run v1.17.3
$ E:\projects\migao-node-service\node_modules\.bin\ts-node ./src/demo.ts
Test the power of ts-node
Done in 1.84s.
以上是使用命令行调用ts-node调试单个ts脚本的方法,日常开发中可以应用于ts语法的检查以及单元测试等内容,非常方便。
对于结合mocha的单元测试运行,官方给出的例子是:
Mocha
Mocha 6
mocha --require ts-node/register --watch-extensions ts,tsx "test/**/*.{ts,tsx}" [...args]
其中使用到了ts-node中的register,这里简单说下我的理解,mocha本身作为cli命令,是在nodejs环境下运行的,由于nodejs本身不支持typescript运行,所以这里需要使用到ts-node的register注册,替换nodejs来运行ts脚本,因此当你在nodejs环境下直接调用ts-node模块运行typescript的时候,便会引发一系列错误,比如无法识别typescript中的import关键字等。同样的,在js脚本中调用ts-node的时候,也需要引入ts-node/require模块,如:
let tsNode = require('ts-node/register');
或:
let tsNode = require('ts-node').register();
在后续vscode中集成ts-node,也是用到ts-node的register模块,这里做一个铺垫。
对于ts-node的其他用途,大家可以自行查看ts-node官方的描述,这里不做赘述。
2.Vscode之launch.json
在Vscode中,launch.json是用于对开发调试的配置文件,默认这个文件是不存在的,需要大家在.vscode目录下手动创建。当然,强大的Vscode也提供了两种方式帮助大家进行创建
使用Ctrl+Shift+P创建
在Vscode中使用Ctrl+Shift+P进入全局搜索,键入 “launch.json”
点击出现的推荐选项,如果是第一次创建,会让你选择是哪一种调试方式:
这里我们由于是调试nodejs环境,因此选择Node.js选项
这个时候,一个初始化默认的launch.json已经帮我们创建好了。我们可以针对项目配置多个调试方案,调试的配置内容都在configurations中。对于配置项的内容,我们参照官方给出的解释:
protocol - debug protocol to use. See section Supported Node-like runtimes above.
port - debug port to use. See sections Attaching to Node.js and Remote debugging.
address - TCP/IP address of the debug port. See sections Attaching to Node.js and Remote debugging.
sourceMaps - enable source maps by setting this to true. See section Source maps.
outFiles - array of glob patterns for locating generated JavaScript files. See section Source maps.
restart - restart session on termination. See section Restarting debug session automatically.
timeout - when restarting a session, give up after this number of milliseconds. See section Attaching to Node.js.
stopOnEntry - break immediately when the program launches.
localRoot - VS Code’s root directory. See section Remote debugging below.
remoteRoot - Node’s root directory. See section Remote debugging below.
smartStep- try to automatically step over code that doesn’t map to source files. See section Smart stepping.
skipFiles - automatically skip files covered by these glob patterns. See section Skipping uninteresting code.
trace - enable diagnostic output.
These attributes are only available for launch configurations of request type launch:
program - an absolute path to the Node.js program to debug.
args - arguments passed to the program to debug. This attribute is of type array and expects individual arguments as array elements.
cwd - launch the program to debug in this directory.
runtimeExecutable - absolute path to the runtime executable to be used. Default is node. See section Launch configuration support for ‘npm’ and other tools.
runtimeArgs - optional arguments passed to the runtime executable.
runtimeVersion - if “nvm” (or “nvm-windows”) or “nvs” is used for managing Node.js versions, this attribute can be used to select a specific version of Node.js. See section Multi version support below.
env - optional environment variables. This attribute expects environment variables as a list of string typed key/value pairs.
envFile - optional path to a file containing environment variable definitions. See section Load environment variables from external file below.
console - kind of console to launch the program (internalConsole, integratedTerminal, externalTerminal). See section Node Console below.
outputCapture - if set to std, output from the process stdout/stderr will be shown in the Debug Console, instead of listening to output over the debug port. This is useful for programs or log libraries that write directly to the stdout/stderr streams instead of using console.* APIs.
autoAttachChildProcesses - track all subprocesses of debuggee and automatically attach to those that are launched in debug mode. See section Automatically attach debugger to Node.js subprocesses below.
This attribute is only available for launch configurations of request type attach:
processId - the debugger tries to attach to this process after having sent a USR1 signal. With this setting, the debugger can attach to an already running process that was not started in debug mode. When using the processId attribute the debug port is determined automatically based on the Node.js version (and the used protocol) and cannot be configured explicitly. So don’t specify a port attribute.
对于各个配置项的内容,官方描述的大多需要通读Vscode的说明文档,这里也不做过多描述,感兴趣的可以自行查看Vscode官网对于这一段的描述(https://code.visualstudio.com/docs/nodejs/nodejs-debugging)
我们直接上代码:
配置好的launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "MigaoServerDebug", // 项目调试配置名称
"type": "node", // 调试的运行环境类型
"request": "launch", // 这里两个选项 launch 或 attach,launch为主配置,attach可以为你提供不同端口但同样代码的服务的调试,详细可参考官网
"args": [ // 固定参数,由字符串数组组成
"${workspaceRoot}/src/bin/www.ts" // 规定了启动文件,这里指定对应项目的启动文件,其中${workspaceRoot}是全局变量,这里提供了多个全局变量方便配置,详情参考官网
],
"runtimeArgs": [ // 运行参数,会在cli和启动文件中间添加
"--nolazy",
"-r",
"ts-node/register" // 这里前文介绍过,要使用ts-node的register模块
],
"sourceMaps": true, // 开启sourceMapsmoshi
"cwd": "${workspaceRoot}", // 运行目录
"protocol": "inspector", // 运行协议,主要针对新旧版本的V8协议进行配置,这里使用新版本的协议
"console": "integratedTerminal" // 日志打印输出,可以针对内部控制台,集成终端和外部控制台进行配置,大家根据情况自行配置
}
]
}
然后通过Vscode的Debug模式启动调试,看到控制台输出的启动提示后,我们就可以在vscode中愉快地断点调试了