在一些除了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等一些構建工具實現,不是很推薦。