Stories

Detail Return Return

如何在vscode中調試typescript? - Stories Detail

前置知識

首先要知道vsocde是無法調試typesript的。所以我們要做的就是將typescript編譯為javascript,然後告訴vscode編譯後的代碼位置,這樣才能進行調試。

流程

1 在項目根目錄創建launch.json配置

// package.json

{
  "name": "debug-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    // .vscode/launch.json會執行這裏的命令
    "build": "tsc"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^5.4.5"
  }
}
// .vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      // 需要調試的代碼入口
      "program": "${workspaceFolder}/src/index.ts",
      // 將代碼編譯為javascript的package命令(對應package.json的script build命令)
      "preLaunchTask": "npm: build",
      // 編譯後的代碼位置
      "outFiles": ["${workspaceFolder}/dist/**/*.js"],
    }
  ]
}

2 配置tsconfig.json

// tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    // 需要跟.vscode/launch.json中的outFiles呼應
    "outDir": "./dist",
    "rootDir": "./src",
     // 必須啓用以支持斷點調試
    "sourceMap": true
  }
}
user avatar tianmiaogongzuoshi_5ca47d59bef41 Avatar grewer Avatar linx Avatar imba97 Avatar wszgrcy Avatar yixiyidong Avatar DingyLand Avatar huangmingji Avatar nznznz Avatar xixindeshoutao Avatar tonyyoung Avatar 79px Avatar
Favorites 37 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.