Making Visual Studio Code automatically compile your TypeScript files into JavaScript.

Title Card

If you prefer a video guide, you can also watch the following steps on YouTube.

With its default settings, Visual Studio Code cannot run or debug TypeScript files. This article describes the necessary configuration steps so that you can run and debug

  • freshly created TypeScript files
  • modified TypeScript files
  • even after restarting VSCode
  • by pressing just a single key

The Problem

Let’s start with a a simple “Hello World” program in a file named hello.ts:

let s: string = "Hello";
console.log(s);

This program contains a tiny bit of TypeScript-specific code, which makes VSCode complain about it when trying to run it via Run -> Run without Debugging and the Node.js plugin:

Syntax Error

What we could do is compile this file manually by invoking the TypeScript compiler in the terminal

tsc hello.ts

and then execute the resulting JavaScript file. But that’s rather tedious and something that the IDE should do for us.

The Solution

First, we create a TypeScript configuration file by invoking the following in a terminal:

tsc --init

In the resulting config file, we active the sourceMap option so that VSCode can match the TypeScript source with the JavaScript source during debugging sessions:

{
  "compilerOptions": {
    // ...
    "sourceMap": true,
    // ...
  }
}

Next, we configure a default build task that will compile the TypeScript code in the background:

Default Build Task 'Watch'

Here, VSCode gives us two TypeScript-specific compiler options because it has detected a TypeScript config file in the project. We choose tsc: watch to make the compiler watch for changes in our files. In the resulting build task file, we also have to add the following to make sure that the compiler continues watching even when we restart VSCode:

{
  "version": "2.0.0",
  "tasks": [
    {
      ...
      "runOptions": {
        "runOn": "folderOpen"
      }
    }
  ]
}

In addition, we have to give the permission for this build task to run automatically. To do so, we type Control-Shift-P, choose “Manage Automatic Tasks in Folder”, and allow it in the next step:

Allow Automatic Tasks

This results in an additional settings.json file in the .vscode folder. After restarting VSCode, the “watch” task is triggered automatically, and TypeScript files are compiled implicitly when they are saved, or before they are run.