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等一些构建工具实现,不是很推荐。

相关推荐
龙在天1 天前
ts中的函数重载
前端
卓伊凡1 天前
非常经典的Android开发问题-mipmap图标目录和drawable图标目录的区别和适用场景实战举例-优雅草卓伊凡
前端
前端Hardy1 天前
HTML&CSS: 谁懂啊!用代码 “擦去”图片雾气
前端·javascript·css
前端Hardy1 天前
HTML&CSS:好精致的导航栏
前端·javascript·css
天下无贼1 天前
【手写组件】 Vue3 + Uniapp 手写一个高颜值日历组件(含跨月补全+今日高亮+选中状态)
前端·vue.js
我是天龙_绍1 天前
🔹🔹🔹 vue 通信方式 eventBus
前端
一个不爱写代码的瘦子1 天前
迭代器和生成器
前端·javascript
拳打南山敬老院1 天前
漫谈 MCP 构建之概念篇
前端·后端·aigc
前端老鹰1 天前
HTML <output> 标签:原生表单结果展示容器,自动关联输入值
前端·html
OpenTiny社区1 天前
OpenTiny NEXT 内核新生:生成式UI × MCP,重塑前端交互新范式!
前端·开源·agent