How to compile .ts automatically with real-time changes in .ts file?


TypeScript is a popular programming language widely used for developing large-scale applications. It is a superset of JavaScript and adds optional static typing, interfaces, and generics to the language. When working with TypeScript, it is crucial to have a smooth development workflow that includes automatically compiling .ts files with real-time changes.

In this article, we will explore the different tools and techniques that can be used to achieve this.

Why Automatically Compile TypeScript Files?

When working on a TypeScript project, developers often make changes to the .ts files. After making changes, they must compile these files to get the corresponding JavaScript files. Compiling TypeScript files manually can be a time-consuming task, especially when the project contains many files.

This is where automatic compilation comes in handy. Automatic compilation can save developers time and effort by compiling TypeScript files in real-time. This means that every time a developer saves changes to a TypeScript file, the file automatically gets compiled into a corresponding JavaScript file.

Syntax

The syntax for automatically compiling TypeScript files with real-time changes depends on the tool or library you choose. In general, the syntax involves running a command or setting up a configuration file to watch for changes in the .ts files and then compile them automatically. Here is a general syntax that can be used −

Command Line −

tsc --watch [path/to/ts/files]

Configuration file −

{
   "compilerOptions": {
      "target": "es5",
      "module": "commonjs",
      "outDir": "dist"
   },
   "include": [
      "src/**/*"
   ],
   "exclude": [
      "node_modules"
   ]
}

Different Tools Used to Compile .ts Files Automatically

Let's look at some popular tools and libraries that can be used to compile TypeScript files with real-time changes automatically.

Tool 1: TypeScript Compile (tsc)

TypeScript Compiler (tsc) is the official TypeScript compiler that comes with the TypeScript installation. It can be used to compile TypeScript files into JavaScript files. The --watch option can be used with tsc to watch for changes in the .ts files and then automatically compile them. Here's an example −

Command Line −

tsc --watch src/app.ts

This command will watch for changes in the app.ts file located in the src directory and then compile it automatically whenever changes are made. The compiled JavaScript file will be output to the same directory.

Example 1

Create src/app.ts and tsconfig.json file using below commands

touch src/app.ts && tsc --init

Now, start the terminal/ command prompt and run the below command to watch the saved changes in the src/app.ts file

tsc –w 

src/app.ts

class Person {
   name: string
   age: number

   constructor(name: string, age: number){
      this.name = name
      this.age = age
   }
   sayHello() {
      console.log(`Hello ${this.name}`)
      console.log(`You are ${this.age} year(s) old.`)
   }
}

const firstPerson = new Person("Aditya", 21)
firstPerson.sayHello()

With this configuration, the .ts files changes will be automatically synced with .js files in real time.

Now to check that these changes are happening, we will use nodemon to re-run the files whenever the .js file changes automatically.

nodemon src/app.js

Final Output

The output that we get in the terminal is −

Hello Aditya
You are 19 year(s) old. 

Tool 2: Webpack

Webpack is a popular build tool for modern web development that can be used to bundle and optimize JavaScript files, but it also has built-in support for TypeScript through the use of loaders. Webpack uses tsc under the hood to transpile the .ts files. ts-loader is used as a glue between webpack and tsc. So, you’ll still need your tsconfig.json file.

Example 2

We will build on the previous example and use Webpack to transpile TS files and bundle the JS files automatically.

To use webpack to transpile TS files to JS files, you will need to install the necessary dependencies, including webpack, webpack-cli, and ts-loader

npm install webpack webpack-cli ts-loader

Once you have installed these dependencies, you can create a Webpack configuration file, webpack.config.js, in your project directory. Here is an example configuration file −

Configuration file (webpack.config.js) −

const path = require('path');
module.exports = {
   entry: './src/app.ts',
   mode: 'development',
   devtool: 'inline-source-map',
   watch: true,
   output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist'),
   },
   resolve: {
      extensions: ['.ts', '.js'],
   },
   module: {
      rules: [{
         test: /\.ts$/,
         use: 'ts-loader',
         exclude: /node_modules/,
      },],
   },
};

In this configuration file, the entry property specifies the entry point for your application, which is a TypeScript file (app.ts in this example). The mode property specifies the build mode (development in this example), and the devtool property specifies the source map type. The output property specifies the output filename and directory, and the resolve property specifies the file extensions to resolve. Finally, the module property specifies the loaders to use for different file types, including the ts-loader for TS files.

The watch option set to true specifies Webpack to run in the background and compile automatically whenever saved changes are detected in the .ts files.

This image shows the directory structure and the contents of the src/app.ts file. Don’t worry dist directory will automatically be created after we start the bundling process.

Now run the following command to start the webpack bundling process −

npx webpack

This will automatically transpile your TS files to JS files in real-time and create a dist/bundle.js file as you make changes to your TS files, and to see changes, we’ll use nodemon.

nodemon dist/bundle.js

The transpiled JS bundle is present in the dist/bundle.js file as specified by the webpack configuration.

Output

The output that we get in the terminal is −

Hello Aditya
You are 19 year(s) old. 

Conclusion

Automatically compiling TypeScript files with real-time changes can save developers a lot of time and effort during development. There are several tools and libraries available that can help achieve this. TypeScript Compiler (tsc), Webpack, and Gulp are some popular choices that can be used to compile TypeScript files with real-time changes automatically. We have discussed two of these tools in this article here.

Each tool has its own syntax and configuration options, so it's important to choose the one that best fits your needs. Whether you're working on a small project or a large-scale application, having a smooth development workflow that includes automatic compilation can help increase productivity and reduce errors.

Updated on: 01-Aug-2023

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements