The goal of this tutorial is to teach you how to compile TypeScript code into JavaScript. TypeScript is a strictly syntactical superset of JavaScript, which adds optional static typing to the language. However, browsers don't understand TypeScript, so we need to compile it into JavaScript.
By the end of this tutorial, you will be able to:
You should have a basic knowledge of JavaScript to follow along with this tutorial.
To compile TypeScript into JavaScript, we first need to install TypeScript. We can do this globally using npm (Node Package Manager) with the following command:
npm install -g typescript
After installing TypeScript, you can use the tsc
command to compile your TypeScript files into JavaScript. For example, if you have a file named main.ts
, you can compile it with:
tsc main.ts
This will create a main.js
file in the same directory.
You can also configure the TypeScript compiler by creating a tsconfig.json
file in your project's root directory. This file specifies the root files and the compiler options required to compile the project.
Here is an example tsconfig.json
file:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./dist",
},
"include": [
"./src/**/*"
]
}
In this configuration:
target
specifies the ECMAScript target version. In this case, we are targeting ES5 for maximum browser compatibility.module
specifies the module code generation. Here, we're using CommonJS.outDir
specifies the output directory for the compiled JavaScript files. Here, we're outputting to a directory named dist
.include
specifies the files or directories that should be included in the compilation.Let's create a simple TypeScript file and compile it to JavaScript.
Create a file named main.ts
with the following content:
// This is a simple TypeScript function
function greet(name: string) {
return "Hello, " + name;
}
// Call the function
console.log(greet("TypeScript"));
In this file, we define a function named greet
that takes a name
parameter of type string
. We then call this function and log the result to the console.
To compile this file, we use the tsc
command:
tsc main.ts
This will create a main.js
file with the following content:
function greet(name) {
return "Hello, " + name;
}
console.log(greet("TypeScript"));
As you can see, the TypeScript code has been compiled into JavaScript.
In this tutorial, you learned how to compile TypeScript code into JavaScript. You also learned how to configure the TypeScript compiler using a tsconfig.json
file.
The next step is to start writing more complex TypeScript code and compile it to JavaScript. You can also explore more configuration options in the TypeScript documentation.
tsconfig.json
file with different configuration options and compile your TypeScript files.Each of these exercises will give you practical experience with TypeScript and its compilation process. Remember to test your JavaScript output to ensure it behaves as expected.