【问题标题】:How to watch and re-run TypeScript on change?如何在更改时查看和重新运行 TypeScript?
【发布时间】:2020-07-22 11:00:27
【问题描述】:

我有一个用 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


【解决方案1】:

您可以同时运行tscnodemon

npx tsc -w & npx nodemon build

或使用带有ts-node的nodemon:

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

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 2010-10-27
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多