TypeScript Compile on Save in Visual Studio Code

We learned how to create the Hello World Example program in the last tutorial. Every time we make a change in the code, we need to run the tsc HelloWorld.ts to compile it to the Javascript. We can instruct the visual studio code to automatically compile the Typescript file to Javascript file whenever we make changes and save the Source file.

Open the Command prompt and create the GettingStarted Folder and then cd into it. Run code . to open the Visual Studio Code

Create a file HelloWorld.ts and the following code

To compile the above code, you need to run the

Now, If you change anything in the above code, you need to run the tsc to generate the Javascript file.

Table of Contents

Typescript configuration file

To Enable Compile on save feature, we first need to create the Typescript Configuration file tsconfig.json.

The tsconfig.json is the file where TypeScript Compiler looks for project configuration and compiler options.

The easiest way to create the tsconfig.json file is to use the following command

This will create tsconfig.json. You can look at the generated file. It has listed all the possible compiler option, with almost all of them commented out.

Another way is to just to create the tsconfig.json and copy the following content.

Compile on Save

Once you created the tsconfig.json, You can enable compile on save feature. There are two ways you can achieve this result

Running the tsc in watch mode

Open the command prompt and cd into the project folder or Click on View -> Terminal in the VS Code Menu. In the command prompt run the following command

This will watch the folder for changes made to our typescript file and immediate run the compiler.

TypeScript Compile on Save. Running Compiler on Watch mode

Using the Build Task

The second option is to hit the (Ctrl+Shift+B) from the VS Code. This will open the Execute Run Build Task window

TypeScript Compile on Save. Using the build task

Select tsc: watch. This will make the TypeScript compiler to watch for changes made to the TypeScript file and run the compiler on each change

Summary

In this tutorial, we learned how to enable compile on save by running tsc on watch mode.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top