vscode 調試 TypeScript

環境

typescript :2.5.2
vscode:1.16.0node

vscode 直接調試 ts 文件

源碼:githubwebpack

圖片描述

安裝 typescript 依賴

npm install typescript --save-dev

添加 tsconfig.json

主要是將 sourceMap 設置爲truegit

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

配置自動編譯

利用 vscode 的 tasks 自動將 ts 編譯爲 js。也能夠使用別的方式編譯,如:gulp,webpack 等。
添加文件: /.vscode/tasks.jsongithub

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for thedocumentation about the tasks.json format
   "version": "0.1.0",
   "command": "tsc",
   "isShellCommand": true,
   //-p 指定目錄;-w watch,檢測文件改變自動編譯
   "args": ["-p", ".","-w"],
   "showOutput": "always",
   "problemMatcher": "$tsc"
}

使用快捷鍵 Ctrl + Shift + B 開啓自動編譯。web

配置調試

調試時,須要配置 vscode 的 launch.json 文件。這個文件記錄啓動選項。
添加或編輯文件 /.vscode/launch.jsontypescript

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/dist/main.js",
            "args": [],
            "cwd": "${workspaceRoot}",
            "protocol": "inspector"
        }
    ]
}

注意 : program 需設置爲你要調試的 ts 生成的對應的 js。
假如須要調試 /src/main.ts,則此處爲 ${workspaceRoot}/dist/main.jsnpm

調試

打開 main.ts,在左側添加斷點,進行調試。json

圖片描述

使用 ts-node 調試 ts 文件

源碼:github
來自:Debugging TypeScript in VS Code without compiling, using ts-node
ts-node 調試 ts 文件時,不會顯式生成 js。假如你不想編譯爲 js 後 再調試,能夠考慮這種方式。gulp

安裝 npm 依賴包

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

配置 tsconfig.json

主要是將 sourceMap 設置爲truees5

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

配置 launch.json

打開 DEBUG 界面,添加 配置
或者編輯 /.vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Current TS File",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/ts-node/dist/_bin.js",
            "args": [
                "${relativeFile}"
            ],
            "cwd": "${workspaceRoot}",
            "protocol": "inspector"
        }
    ]
}

調試

  1. 打開要調試的 ts 文件,添加debugger
  2. 打開 debug 界面。
  3. DEBUG後 選擇 launch.json 中對應的配置,此處爲Current TS File
  4. 點擊運行按鍵或者按 F5 運行。

圖片描述

參考文章

  1. Debugging TypeScript in VS Code without compiling, using ts-node
  2.  VS Code 開發調試 TypeScript
相關文章
相關標籤/搜索