如何在更改时观察并重新运行 TypeScript?

问题描述 投票:0回答:1

我有一个用 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 文件运行输出,以便在我的代码更改时停止输出并重新运行?

node.js typescript tsc
1个回答
5
投票

您可以同时运行

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
© www.soinside.com 2019 - 2024. All rights reserved.