close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than whatโ€™s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

Typescript Transpiler Explained

Typescript Transpiler Explained
Author
Nimrod Kramer
Related tags on daily.dev
toc
Table of contents
arrow-down

๐ŸŽฏ

Learn about the Typescript Transpiler, its benefits, setup, transpilation vs. compilation, controlling options, automation with watch mode, and more. Simplify your Typescript coding experience.

Understanding the Typescript Transpiler is crucial for developers looking to leverage Typescript's advanced features while ensuring compatibility across various platforms. Here's a concise overview:

  • What is Typescript? A Microsoft programming language that extends JavaScript by adding static typing and other features.
  • Why use the Typescript Transpiler? It converts Typescript into plain JavaScript, making your code runnable on web browsers, Node.js, and other environments.
  • Transpilation vs. Compilation: Transpilation transforms code within the same level of abstraction, whereas compilation converts to a lower-level code.
  • Setting up Typescript: Installation involves using npm, initializing a project, and configuring with tsconfig.json.
  • Transpiling Code: The tsc command turns Typescript into JavaScript, handling features like classes and interfaces differently based on the target version.
  • Controlling Transpilation: You can specify the JavaScript version and other options to tailor the output.
  • Automating with Watch Mode: tsc --watch automatically updates JavaScript files upon Typescript file changes.

This guide aims to simplify the process of using the Typescript transpiler, ensuring your project benefits from Typescript's features while maintaining broad compatibility.

Why Use the Typescript Transpiler?

The Typescript transpiler (tsc) turns Typescript into plain JavaScript so it can run in:

  • Web browsers
  • Node.js
  • Deno
  • React Native

This means you can write your code in Typescript and still have it work everywhere. It's great for making sure your code can run in different places without needing special changes.

Here's why you might want to transpile Typescript:

  • Use new JavaScript features that not all systems support yet
  • Make your code better with Typescript's typing system
  • Find bugs when you're still working on your code, not after it's running
  • Make your code easier to work with and understand
  • Keep your team using the same style of code

In short, using tsc to transpile Typescript lets you enjoy all the benefits of Typescript while making sure your app works wherever it needs to. It's a solid choice for any JavaScript project.

Understanding Transpilation

Transpilation vs Compilation

Basis for Comparison Transpilation Compilation
Input Language High-level programming language High-level or low-level programming language
Output Language High-level programming language Low-level programming language
Abstraction Level Input and output at similar abstraction level Input at higher abstraction level than output
Target Environment Runtime environments like web browsers, Node.js etc Machine code to be executed directly
Readability of Output Code Emphasizes readability Readability is not a priority
Performance Comparatively slower Faster execution

Transpilation is about changing code written in one high-level language (like Typescript) into another (like JavaScript) that can run in places like web browsers or on servers using Node.js. Both the original and the new code are pretty similar in terms of complexity.

Compilation, on the other hand, is when code is transformed from a high-level language into a much simpler machine language that computers can directly understand and execute. This process makes the code less human-friendly but more efficient for machines.

Transpiler Capabilities

Transpilers, such as the Typescript transpiler (tsc), go through a few steps to work their magic:

  • Parsing - This is where the transpiler breaks down the Typescript code into smaller parts to understand what each piece does.
  • Transformation - Next, it changes these pieces based on certain rules to make sure they'll work as regular JavaScript.
  • Code Generation - Finally, it puts all these transformed pieces back together into the new JavaScript code.

This process lets developers use cool new features from Typescript and make sure the code can still run in older environments like certain web browsers or JavaScript runtimes. For instance, tsc can take a fancy Typescript feature like arrow functions and turn them into a more traditional function format that older JavaScript versions understand.

So, transpilers help keep your code up-to-date with the latest features without sacrificing compatibility with older systems.

Setting up the Typescript Transpiler

Installing Typescript

First things first, to get started with Typescript, you need to install it. You do this with npm, a package manager that comes with Node.js, by typing this into your terminal:

npm install -g typescript

This command installs Typescript on your computer and lets you use the tsc command, which is the tool that changes your Typescript code into JavaScript. To make sure everything's working, type:

tsc -v

This should show you the version of Typescript you've installed, meaning you're all set.

Initializing a Typescript Project

Now, set up a new Node.js project by running:

npm init

Just answer the questions that come up to create a package.json file. This file keeps track of your project's details.

Then, add Typescript to your project as a development tool:

npm install --save-dev typescript

This step makes sure Typescript is only used for development, not when your project is actually running somewhere.

Create a tsconfig.json file in your project's main folder. This file tells Typescript how to do its job. Here's a simple example:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "strict": true
  }
}

Project File Structure

Organizing your project files helps keep things tidy. Usually, you'll have a set up like this:

/project_root
|- src
   |- index.ts
|- dist
   |- index.js
tsconfig.json
package.json

Put your Typescript files (.ts) in the /src folder. When you run tsc, it will turn them into JavaScript files (.js) and put them in the /dist folder. This way, your original code and the final output are nicely organized in separate places.

Transpiling Typescript Code

Basic Transpilation

Let's start with a basic example of a Typescript class that has some usual features:

class Person {
  private name: string;
  
  constructor(name: string) {
    this.name = name;
  }
  
  greet() {
    console.log(`Hello, my name is ${this.name}!`); 
  }
}

const person = new Person("John");
person.greet();

After running this through the Typescript transpiler (tsc), we get this JavaScript code:

var Person = (function () {
  function Person(name) {
    this.name = name; 
  }
  Person.prototype.greet = function() {
    console.log('Hello, my name is ' + this.name + '!');
  };
  return Person;
})();

var person = new Person("John"); 
person.greet();

You'll notice that the special Typescript parts like access modifiers are gone, leaving us with plain JavaScript code.

Transpilation Errors

Sometimes, the Typescript code might use features that don't work in the JavaScript version you're targeting. For instance:

const add = (x: number, y: number) => x + y; 

Arrow functions are a newer feature. If you're targeting an older version of JavaScript, tsc might flag this as an error.

To fix this, you can change the target option in your tsconfig.json file to "ES6" or newer. This way, arrow functions will be transpiled correctly.

Code Transformation

Here's another example to see how tsc changes code to fit the target JavaScript environment:

interface Person {
  name: string;
  age: number;
}

function greet(person: Person) {
  console.log(`Hello ${person.name}, you are ${person.age} years old!`) 
}

greet({name: "Maria", age: 42}); 

After transpiling, it looks like this:

function greet(person) {
  console.log('Hello ' + person.name + ', you are ' + person.age + ' years old!');
}

greet({name: "Maria", age: 42});

The interface is gone because JavaScript doesn't have interfaces. But tsc still makes sure the code works well in the JavaScript version you're targeting.

sbb-itb-bfaad5b

Controlling Transpilation

Target JavaScript Version

When you're using the TypeScript compiler, you can pick which version of JavaScript (also known as ECMAScript) your TypeScript code should turn into. This is done with the --target option. For instance:

tsc --target ES5 app.ts

This command changes your app.ts file into JavaScript code that works with ES5, a version that most browsers can understand. You can choose different versions depending on where your code will run, like:

  • ES3 - Good for very old browsers
  • ES5 - Works in almost all browsers today
  • ES2015/ES6 - Lets you use newer features like arrow functions
  • ESNext - Includes the very latest features

Picking an older version makes your code work in more places, but newer versions can make your code faster and let you do more.

NoEmit Options

TypeScript has options to stop it from making JavaScript files:

  • noEmitOnError - If your code has mistakes, it won't create a JavaScript file
  • noEmit - Checks your code but doesn't make a JavaScript file

Using noEmitOnError means you won't get broken JavaScript if there are errors in your TypeScript. noEmit is for when you just want to check your code without making a JavaScript file, maybe because you're using another tool like Babel for that.

Other Options

Here are a few more options you might find useful:

Option Description
sourceMap Makes sourcemaps to help you debug
strict Turns on all the strict checking
downlevelIteration Helps with loops in older JavaScript versions
importHelpers Uses helper functions for new JavaScript features

For more details on these and other options, you can check the compiler documentation.

Automating with Watch Mode

Watch mode is a handy feature that lets the Typescript transpiler automatically update your code as soon as you make changes. This means you don't have to run the transpiler by hand every time you tweak your code, saving you a bunch of time and hassle.

Setting Up Watch Mode

Getting watch mode going is easy. Just open up your project folder in your terminal and type:

tsc --watch

This tells the transpiler to keep an eye on your Typescript files and update them the moment you make any changes.

If you want to make sure the whole project gets updated whenever you change any file, you can use:

tsc --watch --preserveWatchOutput --extendedDiagnostics

This does a few things:

  • Looks through all your folders for .ts files to update
  • Keeps the updated .js files around between runs
  • Gives you detailed info on what's happening when files are updated

Now, every time you save a change to a .ts file, the transpiler will quickly update the .js version.

Watch Mode Options

Here are some handy options you can use with watch mode:

  • --verbose - Gives you more details about the updating process
  • --incremental - Saves time by only updating files that have changed
  • --preserveWatchOutput - Doesn't delete your updated files between runs
  • --diagnostics - Provides extra details about the transpiler's work
  • --interactive - Keeps watch mode going until you decide to stop it

You can also pause watch mode, update only the files you're currently working on, and combine it with tools like Yarn or task runners for even smoother workflows. Check out the documentation for more tips and tricks.

Conclusion

The Typescript transpiler, or tsc, is a tool that helps developers use Typescript's advanced features while making sure the code works everywhere, like in browsers and on servers. Here are the main points to remember:

Key Takeaways

  • The transpiler changes Typescript code into regular JavaScript that can run in many places, like web browsers and Node.js. This means more people can use your code without issues.
  • Tsc does a few important steps to change your code, including reading it, making necessary changes, and putting it back together as JavaScript.
  • You can tell tsc exactly how you want your JavaScript to look, like which version to use or whether to include sourcemaps for easier debugging.
  • With watch mode, tsc automatically updates your JavaScript files when you change your Typescript files, making coding faster.
  • Setting things up right helps find mistakes early, use new features safely, makes fixing bugs easier, and keeps everything running smoothly.
  • Using tools like Babel with tsc can make your coding process even better.

In short, the Typescript transpiler lets you write your code with all the cool features of Typescript and makes sure it works well as JavaScript. This way, you get the best of both worlds without any extra headache.

How does TypeScript transpiler work?

Here's a simple breakdown of how the TypeScript compiler turns TypeScript code into JavaScript:

  • Parsing - First, it reads the TypeScript code and breaks it down to understand its structure.
  • Type Checking - Then, it looks for any mistakes in the types you've used.
  • Emitting JavaScript - After that, it turns the TypeScript into regular JavaScript code.
  • Generating Source Maps - It also creates a map that links the JavaScript back to the original TypeScript, which helps in debugging.
  • Transformation - It changes TypeScript-specific features like classes and interfaces into JavaScript code.

So, it basically reads your code, checks it, and then turns it into JavaScript.

How does a transpiler work?

A transpiler changes code from one language to another at about the same level of complexity. Here's how:

  • Parsing - It breaks down the code to understand it better.
  • Analysis - It checks the code to make sure it follows the rules.
  • Transformation - It changes the code so it fits the new language.
  • Code Generation - Finally, it writes out the new code in the target language.

By doing this, a transpiler can change code while keeping its original meaning and structure.

What is the difference between compile and transpile in TypeScript?

Here are the key differences:

  • Target Language - Compiling turns code into machine code, while transpiling turns it into another high-level language.
  • Abstraction Level - Compiling makes code simpler, but transpiling keeps it at the same level.
  • Purpose - Compiling makes code run faster, but transpiling makes it work on different platforms.
  • Process - Compiling might optimize the code more, while transpiling changes it more directly.

In short, compiling makes executable code, and transpiling makes source code in a different language.

How does angular transpiler work?

Angular's transpiler changes TypeScript into JavaScript that works in many browsers. Here's what it does:

  • Reads and checks the TypeScript code.
  • Changes TypeScript features into JavaScript.
  • Adjusts how the code imports and exports things.
  • Adds extra code for Angular-specific features like dependency injection.
  • Gets rid of TypeScript-only code like type annotations.
  • Adds code so the JavaScript works in different browsers.

It turns TypeScript into JavaScript that Angular apps can use in any supported browser.

Related posts

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more