使用npm构建我的打字稿/节点项目
问题描述:
我有一个用TypeScript编写并在节点上运行的项目。我真的很努力地用npm编写脚本来让它开发。 我试图做的是:使用npm构建我的打字稿/节点项目
- 清洁
/dist
文件夹 - 如果
.ts
变化,它编译成/dist
并重新启动节点
这是我第一次尝试,从的scripts
节我package.json
:
"clean": "rimraf dist/**/*",
"build": "tsc",
"watch:start": "npm run clean && nodemon -e ts --exec \"npm run start\"",
"start": "npm run build && node dist/index.js"
如果我和开始我的项目,它陷入了一个循环:
npm run watch:start
> nodemon -e ts --exec "npm run start"
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `npm run start`
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `npm run start`
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
这里是我的第二次尝试,使用npm-run-all
并行运行多个任务:
"clean": "rimraf dist/**/*",
"build": "tsc",
"watch:start": "npm-run-all clean build --parallel --race watch:build watch:serve --print-label",
"watch:build": "tsc -w",
"watch:serve": "nodemon dist/index.js"
这一个效果更好,但它仍然重新启动节点几个时间启动。
建议和改进欢迎!
答
您可以使用tsc-watch,它省略了nodemon的使用,并在任何更改影响应用程序的typescript源时运行。
"scripts": {
"dev": "tsc-watch --onSuccess \"npm start\" ",
"start": "node index.js"
}
它有一个成功处理程序--onSuccess
其重新启动服务器每次的改变,以打字稿源发。
NPM运行dev的
index.js
console.log('node run')
setTimeout(() => console.log(Math.random() * 1000.0), 1000);
控制台
npm run dev
> tsc && concurrently "npm run node-tsc:w"
npm WARN invalid config loglevel="notice"
> [email protected] node-tsc:w C:\Users\Shane\Desktop\so
> tsc-watch --onSuccess "node index.js"
16:49:31 - Compilation complete. Watching for file changes.
node run
709.2226373633507
16:49:36 - File change detected. Starting incremental compilation...
16:49:37 - Compilation complete. Watching for file changes.
node run
974.6349162351444
16:49:41 - File change detected. Starting incremental compilation...
16:49:41 - Compilation complete. Watching for file changes.
node run
935.9043001938232
节点正在改变typecript源后重新启动。
+0
就像一个魅力 –
您应该首先运行tsc来编译您的打字稿应用程序,并且同时运行tsc -w和您的服务器。 –
这就是我在第二次尝试中所做的。我在第一次尝试“干净”之后添加了“构建”部分,并获得了相同的结果。 “tsc -w”在启动时建立所有.ts文件。 –