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
1 2 3 4 | let message = "Hello World"; console.log(message); |
To compile the above code, you need to run the
1 2 3 | tsc HelloWorld.ts |
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
1 2 3 | tsc --init |
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.
1 2 3 4 5 6 7 8 | { "compilerOptions": { "target": "es5", "module": "commonjs", } } |
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
1 2 3 | tsc -w |
This will watch the folder for changes made to our typescript file and immediate run the compiler.
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
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.