Configuring and Running TypeScript in VS Code

Configuring and Running TypeScript in VS Code
Configuring and Running TypeScript in VS Code
As a superset of JavaScript, TypeScript makes JavaScript feel more like a “serious” programming language. Compared with plain JavaScript, TypeScript provides static type checking and syntactic sugar for classes (although this has also been introduced in ES6), making programs more standardized and concise. It provides the necessary foundation for developing large-scale projects with JavaScript. To use TypeScript in Visual Studio Code, some configuration is required. VS Code also provides standard sample projects, and you can quickly get started with a TypeScript project by cloning them.
1. Installing TypeScript
Since TypeScript is only a superset of JavaScript, and TypeScript programs ultimately need to be “compiled” into JavaScript files to run, you first need to install the JavaScript runtime environment—namely Node.js—and then install TypeScript using the npm package manager.
npm install -g typescript
tsc --version # Check whether TypeScript is installed correctly
The official VS Code documentation uses a simple Hello World example project to demonstrate how to use and configure TypeScript (without going into the details of the TypeScript language itself). Create a helloworld folder, and inside it create a helloworld.ts file as follows:
let message: string = 'Hello World';
console.log(message);
Enter tsc helloworld.ts in the terminal to compile the TypeScript file into a helloworld.js file. In this example, you can see that the generated JavaScript file is almost identical to the TypeScript file, although this is not the case in most situations.
When writing TypeScript code, VS Code’s IntelliSense feature works automatically to provide code completion and error checking for programs and variables.
2. The tsconfig.json Configuration File
In the root folder of a TypeScript project, in addition to the usual Node.js project configuration file package.json, you also need an extra tsconfig.json file to tell the editor how to configure TypeScript. This file can be written manually or generated automatically with the tsc --init command. A minimal tsconfig.json example from the official documentation looks like this:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "out",
"sourceMap": true
}
}
Here, the target parameter specifies the JavaScript version to generate, usually ES5, and outDir specifies the folder where the generated JavaScript files will be placed. Normally, the converted JavaScript can become complex and difficult to debug, making it hard to map back to the original TypeScript files one by one. The sourceMap option is intended to preserve the connection between the source files and the compiled files. Setting it to true allows debugging through the .ts files, which is much more convenient.
3. Building and Debugging a TypeScript Project
In VS Code, choose Terminal → Configure Default Build Task, and in the options that appear select a Node.js project. This will automatically generate a tasks.json file similar to the following. After creating this file, you can run the build task through Terminal → Run Task.
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Similarly, under the Run panel, choose to create or open a configuration file, and VS Code will also generate a default launch.json file.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/helloworld.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": ["${workspaceFolder}/out/**/*.js"]
}
]
}
After configuring the necessary parameters in launch.json, you can debug a TypeScript project much like you would debug a modern programming language such as C#: setting breakpoints, stepping through code, and so on. Here, the preLaunchTask includes the build step described earlier, and outFiles corresponds to the output configuration in tsconfig.json.
If the TypeScript project you are writing is meant to run on the front end (client side) rather than under Node.js, and you want to debug it in VS Code, you will first need to install the appropriate browser extension, such as Debugger for Chrome. In that case, the launch.json file will also be different. Once configured, running Run → Start Debugging (F5) will launch Chrome and start debugging inside the browser.
4. Automated Build Tools
In a TypeScript project, if you have to recompile and rerun the code every time you modify a file, productivity becomes very low. For this reason, TypeScript also provides a watch mode that automatically recompiles as soon as a file changes. This can be done simply with the tsc --watch command. Of course, automated build tools such as gulp and grunt can also handle this. Both gulp and grunt have their own pros and cons; here, grunt is used as an example. First, install the following components globally and within the project:
npm install -g grunt-cli
npm install --save-dev grunt
npm install grunt-exec --save-dev
npm install grunt-contrib-watch --save-dev
You also need to create a GruntFile.js file in the project root directory and modify it to enable automatic restart and debugging after the project changes.
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-exec');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
files: ['**/*.ts'],
tasks: ['exec:run_tsc']
},
exec: { run_tsc: { cmd: 'tsc' } }
});
grunt.registerTask('default', ['watch']);
};
After the configuration is complete, simply enter grunt on the command line to enable automatic building and hot monitoring for debugging.


