TypeScript 后端开发中的热重载编译处理

在一些除了nest框架外的一些其他nodejs框架中没有提供对ts编译和热重载,如果使用typescript我们需要自己进行配置。

方法一(推荐)

使用bun运行环境(快)。注:一些不是使用js,ts代码编写的第三方包,可能会有兼容性问题。

复制代码
bun run --hot index.ts

构建为js代码

复制代码
bun build index.ts --target node --outdir ./dist

编译成可执行文件

复制代码
bun build --compile --minify index.ts --outfile ./dist/web

方法二(推荐)

使用deno运行环境(安全) 。deno2.x和bun有同样兼容性问题,deno1.x兼容性更差。

复制代码
deno run --allow-net --watch ./src/index.ts 

编译成可执行文件

复制代码
deno compile --output ./dist/app --allow-net --allow-read ./src/index.ts

方法三(推荐)

使用 ts-node-dev,npm i ts-node-dev安装。

复制代码
ts-node-dev --respawn --transpile-only src/index.ts

方法四

使用tsc配置增量编译,配合concurrently 实现。

tsconfig.json

复制代码
{
  "compilerOptions": {
    "target": "es2016", // 输出目标 JavaScript 版本
    "module": "CommonJS", // 使用 ES 模块
    "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
    "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
    "lib": [
      "ES2016",
      "DOM"
    ],
    "moduleResolution": "node", // 使用 Node.js 模块解析策略
    "outDir": "./dist", // 输出目录
    "rootDir": "./src/", // TypeScript 源代码目录
    "baseUrl": "./", // 设置模块解析的基本路径
    "resolveJsonModule": true, // 支持导入 JSON 文件
    // "emitDeclarationOnly": false, // 只生成声明文件
    "allowJs": true, // 允许导入 JS 文件
    "checkJs": true,
    "sourceMap": true,
    "importHelpers": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true, // 支持与 CommonJS 模块互操作
    "strict": true, // 启用严格模式
    "listEmittedFiles": true, // 打印输出文件
    "listFiles": true,
    "declaration": false, 
    "composite": false, // 启用增量构建
    "incremental": true, // 启用增量编译
    "tsBuildInfoFile": "./.tsbuildinfo", // 增量编译信息文件
    "skipLibCheck": true, // 跳过库类型检查
    "forceConsistentCasingInFileNames": true, // 强制文件名大小写一致
    "paths": {
      "*": [
        "node_modules/*"
      ] // 配置模块路径
    }
  },
  "include": [
    "src/**/*" // 包含所有 src 目录下的文件
  ],
  "exclude": [
    "node_modules" // 排除 node_modules 目录
  ]
}

package.json

复制代码
"a": "concurrently \"npm run c\" \"npm run n\"",
"c": "tsc --watch",
"n": "nodemon --exec node ./dist/bin/www.js --watch ./src --ext ts --legacy-watch",

其它方法

也可以使用webpack、vite、gulp等一些构建工具实现,不是很推荐。

相关推荐
薛定喵的谔10 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙68711 小时前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen12 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
青山Coding14 小时前
Cesium应用(八):物体运动的实现思路
前端·cesium
用户416596736935514 小时前
Android WebView 加载 file:// 离线页面调试教程
android·前端
Asmewill14 小时前
curl命令学习笔记一
前端
我是一只快乐的小螃蟹14 小时前
1.2 ArrayList 源码解析
前端
星栈14 小时前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:再把新建、编辑和交付补上
前端·rust·前端框架
我是一只快乐的小螃蟹14 小时前
1.1 HashMap (JDK1.8) 源码解析
前端
爱勇宝16 小时前
小红花成长新版:模板来了,鼓励也更容易开始
前端·后端·程序员