如何同时执行打字稿监视和运行服务器?

Ton*_*ony 4 command node.js npm typescript package.json

我在nodejs中开发我的项目.我发现如果我需要代码和测试api,我会运行两个控制台,一个是执行typescript watch,另一个是执行server.

我觉得这太麻烦了.我发现github上的其他开发人员已编写过脚本package.json.调用任何命令都很容易.它吸引了如何编写脚本以及我的开发工作流程.

简而言之,打字稿表tsc -w的命令就是运行服务器的命令node app.js.我的想法是合并命令,tsc -w & node app.js但我无法同时处理这两个命令.我该怎么办?谢谢.

Her*_*gon 9

第1步

安装concurrently、使用npmyarn

yarn add concurrently -D   
Run Code Online (Sandbox Code Playgroud)

第2步

使用此命令创建脚本

"scripts": {
    "run": "tsc && concurrently \"tsc -w\" \"nodemon dist/app.js\"",
}
Run Code Online (Sandbox Code Playgroud)

首先运行 tsc 以便您的目录在运行节点时有一些东西

这样你就可以运行你的 Typescript 应用程序了


Mik*_*ank 7

TLDR,如果您喜欢nodemon,这是获取文件监视、编译和执行的直接方法:

nodemon --ext ts --exec 'tsc && node dist/index.js'
Run Code Online (Sandbox Code Playgroud)

可以选择将 tsc 替换为 babel 以加快编译速度。

下面是 package.json 中更完整的示例(带有源映射):

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

安装如果需要,source-map-support作为依赖项,咳咳...源映射支持!否则,--require source-map-support/registerserve上面的脚本中删除。

tsconfig.json

{
  "compilerOptions": {
    ...
    "sourceMap": true,
    "outDir": "dist",
  }
}
Run Code Online (Sandbox Code Playgroud)


bas*_*rat 5

我的想法是将命令合并为tsc -w和node app.js,但我无法同时处理这两个命令.我该怎么办

你有几个选择.最简单的方法是使用ts-node:https://github.com/TypeStrong/ts-node


Uri*_*igo 5

另一个选择是使用nodemon:

tsc -w & nodemon app.js

从Typescript 3.4开始,编译可以更快,因为您可以使用incremental 编译器选项

  • @AviMehenwal `tsc -w` 编译并保持在监视模式,其他部分 `nodemon app.js` 不运行 (3认同)