But Why Another Guide?

I’ve decided to write this short port since I found there are simply too many guides out there which are either out of date, incomplete, inaccurate or just over-complicated.

This is a true dummy’s guide: if you follow these clear instructions carefully you will be debugging within 5-10 minutes.

Hopefully this post will come in handy to you fellow devs.

Let’s Do It!

Install the TypeScript Compiler Globally:

  • npm i -g typescript

Create a New Project Folder:

  • mkdir debug-ts
  • cd debug-ts

Initialize the Project:

  • npm init -y // create package.json file silently
  • tsc –init // create tsconfig.json file

Install Dependencies:

Install the typescript compiler (yes, it is also required locally), ts-node (to run typescript directly) and node.js.type definitions:

  • npm i –save typescript ts-node
  • npm i –save-dev @types/node

Create a Start Script:

Open the project folder in WebStorm and add the following start script to your package.json file:

"scripts": {
"start": "ts-node index.ts"
}

Your package.json file should now look similar to:

{
 "name": "debug-ts",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
   "start": "ts-node index.ts"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "dependencies": {
   "ts-node": "^8.0.3",
   "typescript": "^3.3.3333"
 },
 "devDependencies": {
   "@types/node": "^11.11.3"
 }
}

Write Some Code:

Create a new TypeScript file named “index.ts” and paste in the following code snippet:

import ErrnoException = NodeJS.ErrnoException;
import * as fs from 'fs';

fs.readdir('.', (err: ErrnoException, items: string[]) => {
   if (err) {
       console.error(err.message);
       return;
   }
   
   for (let item of items) {
       console.log(item);
   }
});

Create a Debug Configuration:

Click menu item Run → Edit Configurations…

Click the plus sign (top left) and select Node.js.

Enter Debug Configuration Details:

  • Name: Debugging TS Code
  • Node parameters: –require ts-node/register
  • JavaScript file: index.ts

* NOTE: there are two
dahses preceding the require flag in
the “Node parameters” field.

Finally click the OK button to save and dismiss.

Create a Breakpoint:

Put a breakpoint (click the gutter) on line 11:

Debug Your App:

Click menu item Run → Debug ‘Debugging TS Code’

Within a second or two you should see the breakpoint being hit, from which point you can start debugging your code.

Well done! You are now ready to fight bugs.

Oh, and don’t forget to share – sharing is caring 🙂

-Zacky