npm 如何同时执行typescript watch和running server?

uinbv5nw  于 2022-11-14  发布在  TypeScript
关注(0)|答案(7)|浏览(146)

我在nodejs中开发我的项目。我发现如果我需要编码和测试api,我会运行两个控制台,一个是执行typescript watch,另一个是执行server。
我觉得太麻烦了,我发现github上其他开发者都用package.json写脚本,调用任何命令都很容易,它吸引了我如何写脚本,简化了我的开发流程。
简单来说,看打字稿的命令是tsc -w,运行服务器的命令是node app.js。我的想法是把这两个命令合并成tsc -w & node app.js,但是我不能同时使用这两个命令。我该怎么做?谢谢。

ztyzrc3y

ztyzrc3y1#

我的想法是将命令合并为tsc -w和node app.js,但是我不能同时使用这两个命令。
您有几种选择。最简单的是使用ts-node-devhttps://github.com/whitecolor/ts-node-dev

evrscar2

evrscar22#

步骤1

安装concurrently,请使用npmyarn

yarn add concurrently -D

步骤2

使用以下命令创建脚本

"scripts": {
    "run": "tsc && concurrently \"tsc -w\" \"nodemon dist/app.js\"",
}

首先运行tsc,以便在运行node时您的目录有一些内容
这样,您就可以运行您的Typescript应用程序🚀

pobjuy32

pobjuy323#

另一个选择是使用nodemon:
tsc -w & nodemon app.js
自Typescript 3.4以来,编译速度更快了,因为您可以使用incrementalcompiler option,而且它们在不断改进(包括3.8中对大型项目的有趣更改)。
更新:
我还使用了concurrently,正如HerberthObregon在回答中所说

7gs2gvoe

7gs2gvoe4#

TLDR,如果你喜欢nodemon,这是一个直接的方式来获得文件监视,编译和执行:
nodemon --ext ts --exec 'tsc && node dist/index.js'
可以选择将tsc替换为babel以加快编译速度。
下面是一个更完整的示例,在package.json中(带有源Map):

"scripts": {
  "develop": "nodemon --ext ts --exec 'yarn build --incremental && yarn serve'",
  "build": "tsc",
  "serve": "node --require source-map-support/register dist/index.js",
  ...
},

如果你想要的话,安装source-map-support作为一个依赖项,咳咳...源代码Map支持!否则,从上面的serve脚本中删除--require source-map-support/register
tsconfig.json

{
  "compilerOptions": {
    ...
    "sourceMap": true,
    "outDir": "dist",
  }
}
kjthegm6

kjthegm65#

根据HerberthObregon的回答

第1步:安装软件包

npm install concurrently typescript nodemon --save-dev

步骤2:在package.json中创建这些脚本

"scripts": {
   "build": "tsc",
   "build:watch": "tsc -w",
   "dev": "npm run build && concurrently \"npm run build:watch\" \"npm run serve:watch\"",
   "serve": "node dist/index.js",
   "serve:watch": "nodemon dist/index.js"
},
  • 生成器运行标准的typescript生成
  • 生成:监视在监视模式下运行typescript生成
  • serve提供节点项目(假设tsconfig输出到dest/index/js)
  • serve:只要js输出发生变化,watch就会使用nodemon重新启动节点服务器
  • 开发人员将它们放在一起
lyr7nygr

lyr7nygr6#

这里我想说的是,这里有一个使用ts-node-devconcurrently的解决方案,类似于@HerberthObregon提供的解决方案,但使用的是ts-node-dev而不是nodemon

"scripts": {
    "start": "npm run build && concurrently \"npm run build:watch\" \"npm run dev\"",
    "dev": "tsnd --respawn src/main.ts",
    "build": "tsc -p tsconfig.release.json",
    "build:watch": "tsc -w -p tsconfig.release.json"
}

额外好处:如果您需要帮助来计算tsctsconfig.json,我使用这个node typescript starter的合理默认值。

6mw9ycah

6mw9ycah7#

这里有一个适合我的解决方案

1.安装ts-node和nodemon作为开发依赖项
2.创建脚本"dev" : "nodemon app.ts"

相关问题