Visual studio code debug typescript

TypeScript tutorial in Visual Studio Code

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.

Install the TypeScript compiler

Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc . You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript ( tsc HelloWorld.ts ).

The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally ( -g ) on your computer by:

You can test your install by checking the version.

Hello World

Let’s start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.

mkdir HelloWorld cd HelloWorld code . 

From the File Explorer, create a new file called helloworld.ts .

create new file

Now add the following TypeScript code. You’ll notice the TypeScript keyword let and the string type declaration.

let message: string = 'Hello World'; console.log(message); 

To compile your TypeScript code, you can open the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) and type tsc helloworld.ts . This will compile and create a new helloworld.js JavaScript file.

compiled hello world

If you have Node.js installed, you can run node helloworld.js .

run hello world

If you open helloworld.js , you’ll see that it doesn’t look very different from helloworld.ts . The type information has been removed and let is now var .

var message = 'Hello World'; console.log(message); 

IntelliSense

In VS Code, you can see that you get language features such as syntax highlighting and bracket matching. When you were typing in the editor, you may have noticed IntelliSense, the smart code completions and suggestions provided by VS Code and the TypeScript language server. Below you can see the methods of console

IntelliSense

When you select a method, you then get parameter help and can always get hover information.

parameter help

tsconfig.json

So far in this tutorial, you have been relying on the TypeScript compiler’s default behavior to compile your TypeScript source code. You can modify the TypeScript compiler options by adding a tsconfig.json file that defines the TypeScript project settings such as the compiler options and the files that should be included.

Important: To use tsconfig.json for the rest of this tutorial, invoke tsc without input files. The TypeScript compiler knows to look at your tsconfig.json for project settings and compiler options.

Читайте также:  Максимальное четное число python

Add a simple tsconfig.json that set the options to compile to ES5 and use CommonJS modules.

 "compilerOptions":  "target": "es5", "module": "commonjs"  > > 

When editing tsconfig.json , IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) will help you along the way.

tsconfig.json IntelliSense

By default, TypeScript includes all the .ts files in the current folder and subfolders if the files attribute isn’t included, so we don’t need to list helloworld.ts explicitly.

Change the build output

Having the generated JavaScript file in the same folder as the TypeScript source will quickly get cluttered on larger projects, so you can specify the output directory for the compiler with the outDir attribute.

 "compilerOptions":  "target": "es5", "module": "commonjs", "outDir": "out"  > > 

Delete helloworld.js and run the command tsc with no options. You will see that helloworld.js is now placed in the out directory.

See Compiling TypeScript to learn about other features of the TypeScript language service and how to use tasks to run your builds directly from VS Code.

Error checking

TypeScript helps you avoid common programming mistakes through strong type checking. For example, if you assign a number to message , the TypeScript compiler will complain with ‘error TS2322: Type ‘2’ is not assignable to type ‘string’. You can see type checking errors in VS Code both in the editor (red squiggles with hover information) and the Problems panel ( ⇧⌘M (Windows, Linux Ctrl+Shift+M ) ). The [ts] prefix lets you know this error is coming from the TypeScript language service.

incorrect type error

Quick Fixes

The TypeScript language service has a powerful set of diagnostics to find common coding issues. For example, it can analyze your source code and detect unreachable code which is displayed as dimmed in the editor. If you hover over the line of source code, you’ll see a hover explaining and if you place your cursor on the line, you’ll get a Quick Fix light bulb.

unreachable code detected

Clicking on the light bulb or pressing ⌘. (Windows, Linux Ctrl+. ) brings up the Quick Fix menu where you can select the Remove unreachable code fix.

Debugging

VS Code has built-in support for TypeScript debugging. To support debugging TypeScript in combination with the executing JavaScript code, VS Code relies on source maps for the debugger to map between the original TypeScript source code and the running JavaScript. You can create source maps during the build by setting «sourceMap»: true in your tsconfig.json .

 "compilerOptions":  "target": "es5", "module": "commonjs", "outDir": "out", "sourceMap": true  > > 

Rebuild by running tsc and you should now have a helloworld.js.map in the out directory next to helloworld.js .

With helloworld.ts open in the editor, press F5 . If you have other debugger extensions installed, you need to select Node.js from the dropdown.

The debugger will start a session, run your code, and display the «Hello World» message in the Debug console panel.

debug console output

In helloworld.ts , set a breakpoint by clicking on the left gutter of the editor. You will see a red circle if the breakpoint is set. Press F5 again. Execution will stop when the breakpoint is hit and you’ll be able to see debugging information such as variable values and the call stack in the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ).

debug breakpoint

See Debugging TypeScript to learn more about VS Code’s built-in debugging support for TypeScript and how you can configure the debugger for your project scenarios.

Next steps

This tutorial was a quick introduction to using VS Code for TypeScript development. Read on to learn more about using VS Code’s compiling and debugging support for TypeScript:

  • Compiling TypeScript — Use VS Code’s powerful task system for compiling TypeScript.
  • Editing TypeScript — Specific editing features for TypeScript.
  • Refactoring TypeScript — Useful refactorings from the TypeScript language service.
  • Debugging TypeScript — Configure the debugger for your TypeScript project.

Common questions

Cannot launch program because corresponding JavaScript cannot be found

You’ve likely not set «sourceMap»: true in your tsconfig.json and the VS Code Node.js debugger can’t map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.

Источник

Debugging TypeScript

Visual Studio Code supports TypeScript debugging through its built-in Node.js debugger and Edge and Chrome debugger.

JavaScript source map support

TypeScript debugging supports JavaScript source maps. To generate source maps for your TypeScript files, compile with the —sourcemap option or set the sourceMap property in the tsconfig.json file to true .

In-lined source maps (a source map where the content is stored as a data URL instead of a separate file) are also supported, although in-lined source is not yet supported.

For a simple example of source maps in action, see the TypeScript tutorial, which shows debugging a simple «Hello World» Node.js application using the following tsconfig.json and VS Code default Node.js debugging configuration.

 "compilerOptions":  "target": "es5", "module": "commonjs", "outDir": "out", "sourceMap": true  > > 

For more advanced debugging scenarios, you can create your own debug configuration launch.json file. To see the default configuration, go to the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ) and select the create a launch.json file link.

This will create a launch.json file in a .vscode folder with default values detected in your project.

 // 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", "program": "$/helloworld.ts", "preLaunchTask": "tsc: build - tsconfig.json", "outFiles": ["$/out/**/*.js"]  >  ] > 

VS Code has determined the program to launch, helloworld.ts , included the build as a preLaunchTask , and told the debugger where to find the generated JavaScript files.

There is full IntelliSense with suggestions and information for launch.json to help you learn about other debug configuration options. You can also add new debug configurations to launch.json with the Add Configuration button in the lower right.

launch.json IntelliSense

Also see Node.js Debugging for examples and further explanations.

Mapping the output location

If generated (transpiled) JavaScript files do not live next to their source, you can help the VS Code debugger locate them by setting the outFiles attribute in the launch configuration. Whenever you set a breakpoint in the original source, VS Code tries to find the generated source by searching the files specified by glob patterns in outFiles .

Client-side debugging

TypeScript is great for writing client-side code as well as Node.js applications and you can debug client-side source code with the built-in Edge and Chrome debugger.

We’ll create a tiny web application to show client-side debugging in action.

Create a new folder HelloWeb and add three files: helloweb.ts , helloweb.html , and tsconfig.json with the following content»

let message: string = 'Hello Web'; document.body.innerHTML = message; 
 html>   TypeScript Hello Web    src="out/helloweb.js">   
 "compilerOptions":  "target": "es5", "module": "commonjs", "outDir": "out", "sourceMap": true  > > 

Run tsc to build the app and then test by opening helloweb.html in your browser (you can right-click helloweb.html in the File Explorer and select Copy Path to paste into your browser).

In the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ), select create a launch.json file to create a launch.json file selecting Web App (Edge) as the debugger, or Web App (Chrome) if you prefer.

Update the launch.json to specify the local file URL to helloweb.html :

 "version": "0.2.0", "configurations": [   "type": "msedge", "request": "launch", "name": "Launch Edge against localhost", "url": "file:///C:/Users/username/HelloWeb/helloweb.html", "webRoot": "$"  >  ] > 

The Run and Debug view configuration dropdown will now show the new configuration Launch Edge against localhost. If you run that configuration, your browser will launch with your web page. Open helloweb.ts in the editor and click the left gutter to add a breakpoint (it will be displayed as a red circle). Press F5 to start the debug session, which launches the browser and hits your breakpoint in helloweb.ts .

client-side debug breakpoint

Common questions

Cannot launch program because corresponding JavaScript cannot be found

You’ve likely not set «sourceMap»: true in your tsconfig.json or outFiles in your launch.json and the VS Code Node.js debugger can’t map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.

Источник

Оцените статью