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

相关推荐
Timer@36 分钟前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫1 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81631 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan3 小时前
FastAPI -API Router的应用
前端·网络·python
走粥3 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory0014 小时前
layui select重新渲染
前端·layui
weixin199701080164 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化
九皇叔叔5 小时前
003-SpringSecurity-Demo 统一响应类
java·javascript·spring·springsecurity