Compiling TypeScript code in Visual Studio Code involves the following steps:
1. Installing Visual Studio Code
First, make sure you have Visual Studio Code installed on your computer. You can download and install it from the official website Visual Studio Code.
2. Installing Node.js and npm
To compile TypeScript, you need the Node.js environment. Download and install Node.js from the Node.js official website, as npm is included with Node.js.
3. Installing TypeScript
Open the integrated terminal in Visual Studio Code (you can open it using the shortcut Ctrl + `` ), and enter the following command to install the TypeScript compiler:
bashnpm install -g typescript
4. Creating a TypeScript File
In Visual Studio Code, create a new file and save it with the .ts extension, for example: hello.ts. Then enter TypeScript code, for example:
typescriptfunction greet(person: string): string { return "Hello, " + person; } console.log(greet("World"));
5. Compiling the TypeScript File
Open the terminal again and enter the following command to compile your TypeScript file:
bashtsc hello.ts
This will generate a JavaScript file named hello.js.
6. Running the JavaScript File
Finally, you can run the generated JavaScript file to see the output:
bashnode hello.js
This should print Hello, World in the terminal.
Example Project Setup
To manage and compile multiple TypeScript files more efficiently, create a tsconfig.json file in the root directory of your project. This file is used to specify compilation options, for example:
json{ "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "./dist" }, "include": [ "./src/**/*" ] }
In this configuration, all TypeScript files located in the src directory will be compiled into the dist directory.
Summary
Make sure you have the necessary tools and environment installed, then compile TypeScript files using the tsc command. Using tsconfig.json can more effectively manage compilation options for large projects.