戳藍字「合格前端」關注咱們哦!前端
0. 背景
所謂 「工欲善其事,必先利其器」,讀源碼確實是一件燒腦的事情, 但若是咱們能跟蹤代碼的執行過程,難度就會下降不少。node
給咱們一個調試器,咱們幾乎能夠研究任何複雜項目的實現原理。git
所以,下文咱們先準備調試環境,打算使用了 VSCode 對 TypeScript 源碼進行調試。github
爲此,咱們從克隆源碼倉庫開始,而後詳細的介紹 TypeScript 的調試過程。web
1. 克隆
$ git clone https://github.com/microsoft/TypeScript.git
$ cd TypeScript
$ git checkout v3.7.3
2. 構建
$ npm i
$ node node_modules/.bin/gulp LKG
其中,gulp LKG
,會將 src/
中的源碼編譯到 built/local/
文件夾中, 詳細解釋能夠參考這裏,lib/README.md
。npm
3. 調試
3.1 修改 bin/tsc
TypeScript 源碼中 bin/tsc
,require 的是 lib/tsc.js
, 但 lib/
中的代碼是沒有 source map
的, 咱們要將這裏改爲 require
上一步 gulp
構建出來的 built/local/tsc.js
。json
#!/usr/bin/env node
require('../built/local/tsc.js');

3.2 調試配置
VSCode 菜單 -> Debug -> Add Configuration -> Node.js
VSCode 會新建 .vscode/launch.json
文件,咱們寫入以下內容:gulp
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug TypeScript",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script",
"debug"
],
"port": 9001,
"skipFiles": [
"<node_internals>/**"
],
"stopOnEntry": true,
}
]
}
1)name 字段名字能夠任取,是展現在調試面板中的名字。數組

2)runtimeArgs
數組的第二個元素,對應 VSCode 要調用 npm scripts 名字,一會咱們要修改 package.json
文件,添加一個名爲 debug
的 scripts。微信
3)port
表示調試端口,要與 debug
scripts 指定的端口號保持一致。

4)stopOnEntry
斷點自動停在,調試啓動後執行的第一行代碼那裏。
3.3 debug scripts
打開 package.json
,添加一個名爲 debug 的 scripts
{
...
"scripts": {
"debug": "node --inspect-brk=9001 bin/tsc debug/index.ts",
...
},
...
}
1)npm scripts 名字必須爲 debug
,保持與 .vscode/launch.json
中的 runtimeArgs
數組第二元素一致。
2)--inspect-brk=9001
表示調試端口號,保持與 .vscode/launch.json
中的 port
字段一致。

3)debug/index.ts
是 tsc
編譯的 .ts
文件,咱們須要新建一個 debug
目錄,而後添加一個 index.ts
文件。

debug/index.ts
的內容以下
const i: number = 1;
3.4 啓動調試
使用 VSCode 打開 TypeScript 源碼倉庫的根目錄,而後按 F5
啓動調試。

咱們看到斷點自動停在了 bin/tsc
第一行了,這正是 stopOnEntry
的做用。
總結
以上每一節的介紹,稍微有些分散,如今這裏總結一下,爲了查閱方便。
-
克隆倉庫、安裝依賴、執行構建
$ git clone https://github.com/microsoft/TypeScript.git
$ cd TypeScript
$ git checkout v3.7.3
$ npm i
$ node node_modules/.bin/gulp LKG
-
修改 lib/tsc
爲
#!/usr/bin/env node
require('../built/local/tsc.js');
-
添加 .vscode/launch.json
調試配置
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug TypeScript",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script",
"debug"
],
"port": 9001,
"skipFiles": [
"<node_internals>/**"
],
"stopOnEntry": true,
}
]
}
-
package.json
中添加debug
scripts
{
...
"scripts": {
"debug": "node --inspect-brk=9001 bin/tsc debug/index.ts",
...
},
...
}
-
添加待 tsc
編譯的源碼文件debug/index.ts
const i: number = 1;
-
VSCode 打開 TypeScript 倉庫,按 F5
啓動調試
參考
-
TypeScript v3.7.3:https://github.com/microsoft/TypeScript/tree/v3.7.3 -
Debugging in Visual Studio Code:https://code.visualstudio.com/docs/editor/debugging -
github: https://github.com/thzt/debug-tsc
『合格前端』按期推送高質量博文,不按期進行免費技術直播分享,你想要的都在這了。
❤️ 看完兩件事
若是你以爲這篇內容對你挺有益,我想邀請你幫我兩個小忙:
點個「在看」,讓更多的人也能看到這篇內容
關注公衆號「全棧大佬的修煉之路」,每週學習一個新技術,公衆號後臺回覆「學習資料」免費送給你精心準備的全棧進階資料。
本文分享自微信公衆號 - 全棧大佬的修煉之路(gh_7795af32a259)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。