前言
项目是 TS+Nodejs+Express构建用于前端调试的WEB服务器
基本环境
- nodejs
- vscode
1. 创建项目
在项目文件夹下,生成初始的package.json。
npm init
构建完成后如下图

2.设置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
}
关键配置说明
- outDir 输出文件地址
- "sourceMap": true ,激活源码映射。让vscode明白 输出文件->源码 的映射关系
- "esModuleInterop": true 让nodejs 理解import 并转换为require
- "watch": true 监视文件变化自动编译
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),出现如下界面,创建task.json

修改task.json,添加唯一标识符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调试项目,选择nodejs 环境

生成如下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"
]
}
]
}
关键字段解析
- preLaunchTask 选择刚才生成的task.json。对应label命名
- program 指向我们创建的server.ts
- protocol 调试协议为 inspector
F5启动项目

代码成功进入断点

6.自动重启服务器nodemon
上面的步骤都走完后,我们发现,项目可以成功运行,这时候我们修改server.ts的代码
- res.send('hello world!');
+ res.send('hello china!');
保存后,刷新页面。我们会发现页面并没有变化,还是输出 hello world。这是因为服务器并没有重启,还保留上一次的代码。我们虽然修改了server.ts 文件,但并没有触发输出文件 build/server.js的修改。
这时候,我们就需要 nodemon
- 全局安装nodemon
npm i nodemon -g
- 配置launch.json
+ "runtimeExecutable": "nodemon", // 或者 node-dev
+ "restart": true,
+ "console": "integratedTerminal",

网友评论