前言
項目是 TS+Nodejs+Express構(gòu)建用于前端調(diào)試的WEB服務(wù)器
基本環(huán)境
- nodejs
- vscode
1. 創(chuàng)建項目
在項目文件夾下,生成初始的package.json。
npm init
構(gòu)建完成后如下圖

2.設(shè)置tsconfig.json
這里可以使用命令行,快速生成
tsc --init
修改tsconfig.json
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"allowJs": true,
"checkJs": true,
"outDir": "./bin",
"sourceMap": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"esModuleInterop": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
],
"watch": true
}
關(guān)鍵配置說明
- outDir 輸出文件地址
- "sourceMap": true ,激活源碼映射。讓vscode明白 輸出文件->源碼 的映射關(guān)系
- "esModuleInterop": true 讓nodejs 理解import 并轉(zhuǎn)換為require
- "watch": true 監(jiān)視文件變化自動編譯
3. 添加項目依賴
// 添加基本的node types
npm install @types/node
// 添加express
npm install express --save
npm install @types/express --save
4.新建server.ts
// server.ts
const express = require("express");
const app = express();
app.get('/', function (req: any, res: { send: (arg0: any) => void; }) {
res.send('hello world!');
});
const server = app.listen(3001, function () {
console.log('Listen on port 3001');
});
5. 啟動項目
在vscode 界面 ? + ? + B(Mac)或Ctrl + Shift + B(windows),出現(xiàn)如下界面,創(chuàng)建task.json

image.png
修改task.json,添加唯一標(biāo)識符label
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label":"typescript"
"type": "typescript",
"tsconfig": "tsconfig.json",
"problemMatcher": [
"$tsc"
]
}
]
}
使用vscode調(diào)試項目,選擇nodejs 環(huán)境

image.png
生成如下launch.json文件,并修改
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug TypeScript in Node.js",
"preLaunchTask": "typescript",
"program": "${workspaceFolder}/server.ts",
"cwd": "${workspaceFolder}",
"protocol": "inspector",
"outFiles": [
"${workspaceFolder}/build/*.js"
]
}
]
}
關(guān)鍵字段解析
- preLaunchTask 選擇剛才生成的task.json。對應(yīng)label命名
- program 指向我們創(chuàng)建的server.ts
- protocol 調(diào)試協(xié)議為 inspector
F5啟動項目

image.png
代碼成功進(jìn)入斷點

image.png
6.自動重啟服務(wù)器nodemon
上面的步驟都走完后,我們發(fā)現(xiàn),項目可以成功運行,這時候我們修改server.ts的代碼
- res.send('hello world!');
+ res.send('hello china!');
保存后,刷新頁面。我們會發(fā)現(xiàn)頁面并沒有變化,還是輸出 hello world。這是因為服務(wù)器并沒有重啟,還保留上一次的代碼。我們雖然修改了server.ts 文件,但并沒有觸發(fā)輸出文件 build/server.js的修改。
這時候,我們就需要 nodemon
- 全局安裝nodemon
npm i nodemon -g
- 配置launch.json
+ "runtimeExecutable": "nodemon", // 或者 node-dev
+ "restart": true,
+ "console": "integratedTerminal",

image.png