我有一个用 TypeScript 编写的非常简单的应用程序:
src/index.ts
import * as http from "http";
const server = http.createServer((request, response) =>
{
response.end("Hello, World");
});
server.listen(3000);
然后是我的 TypeScript 配置:
tsconfig.json
{
"compilerOptions": {
// Output options
"target": "es5",
"lib": [
"es2016"
],
"module": "commonjs",
"outDir": "./build",
}
}
我可以使用
npx tsc
构建代码,然后使用 node ./build/index.js
运行它,在浏览器中访问 http://localhost:3000 时,我会看到消息“Hello, World”——到目前为止一切都很好
现在使用
npx tsc -w
我可以观察文件以查看它们是否发生变化,并在发生这种情况时重新编译它们。该命令“永远”运行(直到停止),因此它阻止我在同一终端中运行 node ./output/index.js
。使用多个终端窗口或终端多路复用器,我可以非常简单地运行 node ./output/index.js
,但如果重新编译我的代码,该文件将不会重新运行。这意味着,如果我将字符串“Hello, World”更改为“Hello, Steven”,我将看不到更改,直到我手动停止服务器并重新启动它
有没有办法像这样观看我的 TypeScript 文件并运行输出,以便在我的代码更改时停止输出并重新运行?
您可以同时运行
tsc
和 nodemon
:
npx tsc -w & npx nodemon build
或将nodemon与ts-node一起使用:
npx nodemon -x ts-node -e ts src
# to run even if there are TS errors:
npx nodemon -x 'ts-node --log-error' -e ts src
ts-node-dev
:
npx ts-node-dev src