且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Visual Studio Code 在保存时编译

更新时间:2022-12-04 18:32:14

2018 年 5 月更新:

自 2018 年 5 月起,您不再需要手动创建 tsconfig.json 或配置任务运行器.

  1. 在您的项目文件夹中运行 tsc --init 以创建 tsconfig.json 文件(如果您还没有).
  2. Ctrl+Shift+B 在 VS Code 中打开任务列表并选择 tsc: watch - tsconfig.json.
  3. 完成!每次保存文件时都会重新编译您的项目.
  1. Run tsc --init in your project folder to create tsconfig.json file (if you don't have one already).
  2. Press Ctrl+Shift+B to open a list of tasks in VS Code and select tsc: watch - tsconfig.json.
  3. Done! Your project is recompiled on every file save.

您的工作区中可以有多个 tsconfig.json 文件,并根据需要一次运行多个编译(例如,前端和后端分开).

You can have several tsconfig.json files in your workspace and run multiple compilations at once if you want (e.g. frontend and backend separately).

您可以使用构建命令执行此操作:

You can do this with Build commands:

创建一个简单的 tsconfig.json"watch": true(这将指示编译器监视所有已编译的文件):

Create a simple tsconfig.json with "watch": true (this will instruct compiler to watch all compiled files):

{
    "compilerOptions": {
        "target": "es5",
        "out": "js/script.js",
        "watch": true
    }
}

注意 files 数组被省略,默认情况下,所有子目录中的所有 *.ts 文件都会被编译.您可以提供任何其他参数或更改target/out,只需确保将watch 设置为true.

Note that files array is omitted, by default all *.ts files in all subdirectories will be compiled. You can provide any other parameters or change target/out, just make sure that watch is set to true.

配置你的任务(Ctrl+Shift+P -> Configure Task Runner):

Configure your task (Ctrl+Shift+P -> Configure Task Runner):

{
    "version": "0.1.0",
    "command": "tsc",
    "showOutput": "silent",
    "isShellCommand": true,
    "problemMatcher": "$tsc"
}

现在按 Ctrl+Shift+B 构建项目.您将在输出窗口 (Ctrl+Shift+U) 中看到编译器输出.

Now press Ctrl+Shift+B to build the project. You will see compiler output in the output window (Ctrl+Shift+U).

保存时编译器会自动编译文件.要停止编译,请按 Ctrl+P -> >任务:终止正在运行的任务

The compiler will compile files automatically when saved. To stop the compilation, press Ctrl+P -> > Tasks: Terminate Running Task

我专门为此答案创建了一个项目模板:typescript-node-basic

I've created a project template specifically for this answer: typescript-node-basic