自学内容网 自学内容网

【实战笔记】TypeScript 服务端热更新配置全解(含 ts-node-dev + 路径别名 + VSCode 调试)

【实战笔记】TypeScript 服务端热更新配置全解(含 ts-node-dev + 路径别名 + VSCode 调试)


很久之前写过一篇 TypeScript 服务端热更新,不过当时还没有很注重后端的部分,只是想快速的搭建 UI,然后测试一些新做的功能。不过这次开始写了 MERN 的一个项目之后就发现,用 concurrentlynodemon 的解决方法还是不太成熟,尤其是两个大问题没有办法解决:

  • debugger

    使用 concurrentlynodemon 监听的还是编译后的代码,这也就意味着如果想要打断点,在编译前的 TS 代码中进行 debug,这个操作就有些力有不怠

  • path 的变化

    这个是从相对路径改成绝对路径的导入方法,之前导入的方法基本都是 import {} from '../ 这种,最近改成了 import { AuthError, NotFoundError } from "@/errors"; 这种

    主要是这样层级结构看的比较明显,知道自己是在哪一层

    不过使用 concurrentlynodemon 还是老问题,编译的结果和路径不太对,没有办法找到正确的路径

    现在想想可能和 package.json 没配置好也有关系……不过既然有了更好的解法,暂时就不去考虑之前的问题了

折腾了一下,最终还是找到了合适的方法去进行配置

先简单贴一下自己项目大概的路径:

project-root/
├── backend/
│   ├── tsconfig.json
│   ├── package.json
│   ├── server.ts
│   ├── controllers/
│   ├── services/
│   └── ...
├── package.json
└── frontend/ (optional)

package.json

首先是 package.json:

{
  "_moduleAliases": {
    "@": "./"
  },
  "scripts": {
    "start": "ts-node-dev --respawn --transpile-only -r tsconfig-paths/register server.ts",
    "start:debug": "ts-node-dev --respawn --transpile-only --inspect=9229 -r tsconfig-paths/register server.ts",
    "build": "tsc"
  }
}

_moduleAliases 是用 @ 代表绝对路径时会用上的,如果项目里不打算这么配置,可以忽略这个

下面的指令的 args 分别代表:

  • --respawn 程序崩溃时重新 attach session/debugger,而不是直接退出

  • --transpile-only 只编译,不生成真正的 dist 文件夹和下面的文件 & 忽略类型检查

    这个 flag 不加也不会生成真正的 dist 文件夹和下面的文件,但是不会忽略类型检查,相对而言运行就会慢很多

    ts-node-dev 默认就不会产出编译文件

  • --inspect=9229 开启 node 的调试端口,可以让 vscode 进行连接

  • -r tsconfig-paths/register 预加载 tsconfig-paths/register 这个模块,也是对 _moduleAliases 的支持,不用可以无视

如果只想要进行类型检查,可以加一条这个指令:

"typecheck": "tsc --noEmit"

运行 typecheck 就可以进行针对类型的检查了

tsconfig

然后是 tsconfig 的配置:

{
  "compilerOptions": {
    /* Projects */
    "target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
    "experimentalDecorators": true /* Enable experimental support for legacy experimental decorators. */,

    /* Modules */
    "module": "CommonJS" /* Specify what module code is generated. */,
    "rootDir": "./" /* Specify the root folder within your source files. */,
    "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
    "baseUrl": "./" /* Specify the base directory to resolve non-relative module names. */,
    "paths": {
      /* Specify a set of entries that re-map imports to additional lookup locations. */
      "@/*": ["./*"]
    },

    /* Emit */
    "sourceMap": true /* Create source map files for emitted JavaScript files. */,
    "outDir": "dist" /* Specify an output folder for all emitted files. */,

    /* Interop Constraints */
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

    /* Type Checking */
    "strict": true /* Enable all strict type-checking options. */,

    /* Completeness */
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  },
  "include": ["**/*.ts", "**/*.d.ts"],
  "exclude": ["node_modules", "dist"]
}

其实这里主要解决的也就是 modules 下面那块的内容了,这也是针对使用 @ 作为绝对路径的解决方案。这一块更多的和 build 有关系,就是 tsc 指令,跑测试环境,也就是 HMR 这块差异不是特别大

vscode

这里就是贴一下 vscode 的配置:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach Backend Debugger",
      "type": "node",
      "request": "attach",
      "port": 9229,
      "restart": true,
      "timeout": 10000,
      "cwd": "${workspaceFolder}/backend",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}

这样配置完的效果主要是可以在 vscode 里比较方便的 debug,比如:

在这里插入图片描述

在这里插入图片描述

顺带一提,当前的 debugger 是 attach 模式,也就是说:

  • 和主程序是分开的,主程序(dev 模式)可以一直运行
  • 需要的时候再 attach 一个 debugger session

如图:

在这里插入图片描述

如果想要直接在 vscode 里面运行,可以把 "request" 的模式改成 launch

这个看具体的业务需求,比如说我现在用 monorepo 跑整个项目,同时启动前端和后端,所以不需要额外的 launch,这里就用 attach 比较合适。但是如果觉得 monorepo 跑起来有些问题不太方便,那么单独设立不同的 debugger 进行 launch 也可以

还是像我提到的那样,这个具体看业务/开发需求

chrome debugger

正确配置好了后,chrome 也会提供一个 debugger:

在这里插入图片描述

不过我试着打了下断点,但是没办法直接在这儿暂停,可能还需要一些额外的配置吧……总体来说问题不是很大,毕竟 vscode 那边是可以正常 debug 的,chrome 这个算是锦上添花吧,不能工作也不会强求


原文地址:https://blog.csdn.net/weixin_42938619/article/details/147200937

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!