乐闻世界logo
搜索文章和话题

How to compile Typescript with Visual Studio Code?

1个答案

1

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:

bash
npm 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:

typescript
function 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:

bash
tsc 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:

bash
node 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.

2024年7月29日 13:47 回复

你的答案