您现在的位置是:主页 > Web前端技术 > Web前端技术
如何解决使用nodejs+koa+typescript集成和自动重启的问题开发技术
IDCBT2021-12-28【服务器技术】人已围观
简介这篇文章主要为大家展示了“如何解决使用nodejs+koa+typescript集成和自动重启的问题”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下
这篇文章主要为大家展示了“如何解决使用nodejs+koa+typescript集成和自动重启的问题”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何解决使用nodejs+koa+typescript集成和自动重启的问题”这篇文章吧。
- 版本说明
Node.js: 16.13.1
创建如下目录结构
project ├── src │ └── server.ts ├── package.json └── tsconfig.json
package.json
可以使用 yarn init -y
生成tsconfig.json
可以使用 tsc --init
生成(需要全局或在项目中安装 typescript
包才可以使用 tsc
命令)
注意:
@tsconfig/node16
包需要根据 Node.js
的版本变化,我电脑上安装的是 16.x.x
的版本,所以用的是 @tsconfig/node16
,具体看 tsconfig/bases 中的说明,当然也可以完全不用安装这个包,这个包优点是公用性和主流推荐配置
typescript
如果已经全局安装过了,就从下面的命令中移除它
concurrently 是一个并发执行多个命令的工具包
nodemon 是一个监听文件变化自动重启程序的工具包
yarn add koa yarn add typescript @tsconfig/node16 @types/node @types/koa concurrently nodemon -D填充内容src/server.ts
import Koa from 'koa'; const server: Koa = new Koa(); const port: number = 3000; server.use((ctx: Koa.DefaultContext) => { ctx.body = 'hi koa'; }); server.listen(port, () => { console.log(`Node.js v${process.versions.node}`); });tsconfig.json
注意:extends
字段的值根据你安装的包名 @tsconfig/node**
替换
{ "extends": "@tsconfig/node16/tsconfig.json", "compilerOptions": { "baseUrl": ".", "rootDir": "src", "outDir": "dist", "noImplicitAny": true, }, "include": [ "src/**/*" ] }package.json
"scripts": { "build-ts": "tsc", "build": "yarn build-ts", "debug": "yarn build && yarn watch-debug", "serve-debug": "nodemon --inspect dist/server.js", "serve": "node dist/server.js", "start": "yarn serve", "watch-debug": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"yellow.bold,cyan.bold,green.bold\" \"npm:watch-ts\" \"npm:serve-debug\"", "watch-node": "nodemon dist/server.js", "watch-ts": "tsc -w", "watch": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"yellow.bold,cyan.bold,green.bold\" \"npm:watch-ts\" \"npm:watch-node\"" }标签:很赞哦! ()