VSCode使用ts-node 調試TypeScript代碼


 

TS-NODE

可以看出這些不足都來自於一個根本原因,運行之前需要編譯。后來我就發現了一個很強大的工具ts-node,來看下ts-node的簡介:

TypeScript execution environment and REPL for node.

簡單的說就是它提供了TypeScript的運行環境,讓我們免去了麻煩的編譯這一步驟。最簡單的例子,在注冊ts-node之后,我們就可以直接加載並運行ts文件

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

// 這樣就能直接加載並運行 ./ts-code.ts...
require('./ts-code');

TS Config

為了斷點調試,我們需要在tsconfig.json中開啟sourceMap

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

VSC Launch.json 配置

為ts-node注冊一個vsc的debug任務,修改項目的launch.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相關的快捷鍵,參考

  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即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM