我以前写过一篇用vsc+gulp来自动编译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');
为了断点调试,咱们须要在tsconfig.json中开启sourceMapnpm
{ "compilerOptions": { "module": "commonjs", "target": "es5", "noImplicitAny": true, "outDir": "./dist", "sourceMap": true }, "include": [ "src/**/*" ], }
为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
{ "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" }
在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