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

ste*_*esu 5 node.js typescript tsc

我有一个用 TypeScript 编写的非常简单的应用程序:

src/index.ts

import * as http from "http";

const server = http.createServer((request, response) =>
{
    response.end("Hello, World");
});

server.listen(3000);
Run Code Online (Sandbox Code Playgroud)

然后我的 TypeScript 配置:

tsconfig.json

{
    "compilerOptions": {
        // Output options
        "target": "es5",
        "lib": [
            "es2016"
        ],
        "module": "commonjs",
        "outDir": "./build",
    }
}
Run Code Online (Sandbox Code Playgroud)

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

che*_*som 5

你可以同时tsc运行:nodemon

npx tsc -w & npx nodemon build
Run Code Online (Sandbox Code Playgroud)

或将 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
Run Code Online (Sandbox Code Playgroud)

或者只是使用ts-node-dev

npx ts-node-dev src
Run Code Online (Sandbox Code Playgroud)