How to debug TypeScript in Chrome
How to debug TypeScript in Chrome

How to debug TypeScript in Chrome

A software bug is a programming error or unexpected behavior of a software program. Debugging refers to the process of inspecting and removing bugs in software systems. Programmers use various techniques for debugging; some developers write outputs to the terminal, while others use debugger tools to execute and monitor source code.

The Google Chrome web browser offers an inbuilt debugger with the DevTools module for debugging JavaScript. Chrome DevTools implements support for source maps and can inspect both Node.js and Deno debugger instances. So, whether you use TypeScript in a client-side app (i.e., a TypeScript-based React app) or in a server-side app, you can use Chrome for debugging.

How Chrome DevTools lets you debug TypeScript

Web browsers have inbuilt support for JavaScript and WebAssembly, but not for TypeScript. So, how can we debug TypeScript in Chrome if it doesn’t natively execute TypeScript? Chrome and all standard web browsers support processing JavaScript?source maps.

A JavaScript source map typically maps a particular form of a specific JavaScript source code to a JavaScript source code the browser executes. For example, it’s hard to debug a minified JavaScript file in the browser, but if you use a source map, you can easily debug the readable JavaScript file while executing its minified version. Similarly, you can debug a TypeScript file when you run its transpiled JavaScript version in Chrome.

The official TypeScript compiler,?tsc, can generate source maps during the transpilation process, so now we can write TypeScript code, transpile to JavaScript along with a source map, and debug TypeScript code in the browser while executing the transpiled JavaScript code.

Server-side runtimes like Node and?Deno, where we can run JavaScript/TypeScript, listen to Chrome DevTools debugger events via v8. This is how we can debug server-side TypeScript code in Chrome!

Debugging any TypeScript file: Manual configuration

When you use frontend frameworks to build your apps, their TypeScript templates typically come with pre-included TypeScript compiler configurations and automatically generate source maps for you. But in some scenarios, we have to configure the TypeScript compiler, generate our own source maps, and manually link our transpiled TypeScript files using the HTML?script?tag.

This is a great way to learn how to debug TypeScript in Chrome because that manual configuration and setup helps us understand the TypeScript debugging internals. Let’s prepare a development environment to debug any client-side TypeScript file in Chrome.

First, create a new npm project in any directory you like, as follows:

npm init
# --- or ---
yarn init        

Next, install the?typescript?package:

npm install typescript
# --- or ---
yarn install typescript        

Now, generate the TypeScript compiler configuration file:

npx tsc --init        

The default configuration won’t enable source map generation, so we need to edit the auto-generated configuration file. Uncomment the following line in?tsconfig.json?to enable source map generation:

"sourceMap": true,        

Add an npm script to generate JavaScript by modifying your?package.json:

"scripts": {
  "build": "npx tsc"
},        

Now, we can use either the?npm run build?or?yarn build?command to transpile TypeScript files. We’ll debug the following TypeScript code:

function sayHello(name: string): void {
    let message = `Hello ${name}!`;
    console.log(message);
    if(name == 'TypeScript') {
        console.log('.ts');
    }
    else if(name == 'JavaScript') {
        console.log('.js');
    }
}

sayHello('TypeScript');
sayHello('JavaScript');        

Add the above code into?main.ts. Next, use?main.js?in?index.html:

<script src="./main.js"></script>        

Generate?main.js?and?main.js.map?(our source map) with the following command:

npm run build
# --- or ---
yarn build        

Serve the web content in?https://localhost:3000?with the following command:

npx serve        

The above code starts a static server (Vercel’s?serve) in port?3000. Open the URL in Chrome, open the DevTools, and click the?Source?tab. You’ll see?main.ts?as follows:

No alt text provided for this image
Opening a TypeScript source file in Chrome DevTools

Try to add a breakpoint and reload the app. You can debug TypeScript just as you debug JavaScript in Chrome:

No alt text provided for this image
Setting a breakpoint in a TypeScript source file

Chrome loads the source map automatically, since the TypeScript compiler appends the source map filename to?main.js:

//# sourceMappingURL=main.js.map        

The?debugger?keyword also works with TypeScript debugging. Add?debugger?after the?console.log(message);?statement and reload the app:

No alt text provided for this image
Using the debugger keyword in a TypeScript file

For experimentation purposes, try removing the source map file (main.js.map) and debugging?main.ts. The?main.ts?file will disappear from the source panel because TypeScript debugging works based on source maps.

With this approach, it’s possible to debug TypeScript code bundled with either?webpack?or?Rollup. You can enable debugging TypeScript in Chrome by adding an auto-generated source map to your web directory.

Debugging in frontend frameworks: Automatic configuration

Earlier, we learned how TypeScript debugging works in Chrome by using a manual configuration. But as we mentioned, almost all frontend frameworks/libraries offer pre-implemented TypeScript templates, which typically include compiler configurations to generate source maps. These make it so that when you run your app in developer mode, TypeScript debugging is automatically enabled in Chrome.

Now, we’ll create a React app with Create React App’s?official TypeScript template?to learn how to debug TypeScript apps built with modern frontend frameworks. Run the following command to create a new TypeScript-React app:

npx create-react-app my-app --template typescript
#--- or --- 
yarn create react-app my-app --template typescript        

Now, add the following code to your?App.tsx?file:

import React, { useState } from 'react';
import './App.css';

function App(): JSX.Element {
  const [message, setMessage] = useState('');

  function generateMessage(name: string): string {
    let message: string = `Hello ${name}!`;
    return message;
  }

  function handleClick(): void {
    setMessage(generateMessage('TypeScript'));
  }

  return (
    <div>
      <div>{message}</div>
      <button onClick={handleClick}>Say hello</button>
    </div>
  );
}

export default App;        

The above code renders a greeting message when we click the?Say hello?button. Run the project with the following commands to start debugging TypeScript:

npm start
# --- or ---
yarn start        

Assume that you need to set up a breakpoint for line 8 of?App.tsx. Since we have multiple source files, we can easily navigate to?App.tsx?by pressing Control+P:

No alt text provided for this image

Now, set up the breakpoint and click the button. The DevTools debugger works as expected for TypeScript:

No alt text provided for this image

Try to use the?Call stack?section to monitor TypeScript function calls:

No alt text provided for this image

Every debugger feature works for TypeScript debugging because of source maps. The React scripts module does real-time TypeScript compilation, so you can fix TypeScript programming errors by checking Chrome or your terminal.

Let’s send an integer to the?generateMessage?function just for experimental purposes:

function handleClick(): void {
  setMessage(generateMessage(1));
}        

Now, you will see TypeScript compilation errors on Chrome and the terminal:

No alt text provided for this image
The React development environment shows TypeScript compilation issues

要查看或添加评论,请登录

社区洞察

其他会员也浏览了