Compile Your TypeScript File Automatically

In this post, we are going to learn how to compile our TypeScript file automatically.

As we know, after writing any TypeScript file, we need to compile it every time and based on that, the .js file will be generated. So, every time, we should compile the TypeScript file by writing the command in the console. Then only can we see the output.

But I'm going to share two different ways to perform the compilation of a TypeScript file automatically. Let's see these two ways with an example.

Using tsconfig.json file

For that, we need to create one JSON file named tsconfig.json into our working directory. The code will look like below.

{

"compilerOptions": {

"target": "es5",

"module": "commonjs",

"sourceMap": true,

}

}

As you can see, in the above code snippet of the tsconfig file, there are a few parameters for JSON files related to compilation. For the automated compilation of a TypeScript file, we need to add one more line.

"watch":true

Here, "Watch" keyword is used to watch any unseen changes or updates in any TypeScript file or a complete working folder. We compile it using TypeScript compiler.

You can find the complete code for tsconfig.json below.

{

"compilerOptions": {

"target": "es5",

"module": "commonjs",

"sourceMap": true,

"watch":true

}

}

Another way of automating the TypeScript compilation is by using command line interface or the Command Prompt.

The second way is pretty simple to achieve; we just need to write a single line to watch any changes in our TypeScript file.

Just open a terminal window and write the following command.

tsc *.ts --watch

With the help of the above TypeScript command, it will look for any modification in the working directory or folder and if any changes are found, it automatically compiles and converts it into a JavaScript file.

After executing the above command, you will get a compilation message somewhat like,

Conclusion

So, using these two ways, you can make the compilation task automatic.