How to Debug Nodejs, TypeScript Code in VSCode
Tags: typescript, tutorial, javascript, vscode
Published: 2020-03-01 04:27:59

##Hi Guys Good Day!




It's been almost two years since I've been using __TypeScript__ in my projects. One of the problems that I was having when starting using __TypeScript__ in __VSCode__ was how to debug it. Yea, __TypeScript__ compiles to plain old __JavaScript__, we could debug the output __JavaScript__ code but I don't want to do that and also the __JavaScript__ output code is old but not that old it depends on your configuration. So, I wanna show you how to debug __TypeScript__ code with __VSCode__.

And also I wanna mention, __TypeScript__ is one of the most popular programming languages right now. Check out these links.

[State of JS - JavaScript Flavors](https://2019.stateofjs.com/javascript-flavors/)
[Stack Overflow Survey - 2019](https://insights.stackoverflow.com/survey/2019#most-loved-dreaded-and-wanted)
[RedMonk - Most Programming Languages - January 2020](https://redmonk.com/sogrady/2020/02/28/language-rankings-1-20/)

So, Let's start coding.

First, you need to have __Node.js__ and __VSCode__ installed on your computer and __TypeScript__. The links are down below.

[Node.js](https://nodejs.org/en/) 
[VSCode](https://code.visualstudio.com/)

To install __TypeScript__, run this command after installing __Nodejs__.

```
npm i -g typescript
```

After installing __TypeScript__ globally, from your desktop run these commands.

```cmd
 md typescript-debug && cd typescript-debug && code .
```

Basically what this means is that we are making a directory (__md__) that has a name of __typescript-debug__ and changing our current directory (__cd__) __Desktop__ to __typescript-debug__ and opening the __VSCode__ in the  __typescript-debug__ directory with the (__code .__) command.

Inside the directory, run these commands.

```cmd
 npm init --y && tsc --init
```

What these commands mean is that where initializing a Node project and using the default configuration(__npm init --y__) and we're gonna use TypeScript in this project (__tsc --init__).

And lastly, (bear with me) we're gonna install __express__ and the type definitions for __express__ module using these commands.
```cmd
  npm i -P express && npm i -D @types/express
```
__npm i__ is alias for __npm install__. __-P__ means that the package is a __Dependency__ in our project and __-D__ means that the package is a __Development Dependency__ in our project.


Our _package.json_ file.

```json
{
  "name": "typescript-debug",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {},
  "scripts": {
    "start": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
```

Our _tsconfig.json_ file.

```json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "ES2015",
      "DOM"
    ],
    "sourceMap": true,
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "noEmitOnError": true,
    "watch": true
  },
  "exclude": [
    "node_modules"
  ]
}
```

Ok, I'm gonna explain the most important parts in the __tsconfig.json__ config.

__exclude__ - The files or directories that we don't want to be compiled. In this example, we don't want the typescripts files inside the __node_modules__ folder to be compiled to javascript.

__target__ - The target version of our javascript output code.

__lib__ - This is a list of the helper libraries that we're gonna use in our typescript code and also in the compilation.

__sourceMap__ - A boolean indicating if we want a source map file for each typescript file.

__outDir__ - The path or folder name to our javascript output code.

__rootDir__ - The root directory for our typescript files.

__strict__ - A boolean indicating if we want strict checking in our typescript code.

__esModuleInterop__ - This option needs a lot more explanation. So, I'm gonna just give you an example. This is a boolean value. 

If we set this to <code>false</code>. Our import statement would like this.
```ts
import * as express from 'express';
```

If we set this to <code>true</code>. Our import statement would like this.
```ts
import express from 'express';
```

For more details, read [this](https://stackoverflow.com/questions/56238356/understanding-esmoduleinterop-in-tsconfig-file).

__noEmitOnError__ - A boolean indicating if an error occurred in type checking 
will not emit or compile javascript code.

__watch__ - A boolean indicating that we run the compiler in watch mode. If any files change in our __rootDir__, it will compile new files automatically.



Our _launch.json_ file inside the __.vscode__ folder.

```json
{
    // 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": "${workspaceFolder}/src/app.ts",
            "sourceMaps": true,
            "trace": "all",
            "outFiles": [
                "${workspaceFolder}/build/**/*.js"
            ]
        }
    ]
}
```

And lastly, the __app.ts__ file inside the __src__ folder.

```ts
import express, { Request, Response } from 'express';

const app: express.Application = express();
const port: number = 3000;


app.get('/', (req: Request, res: Response) => {
    res.send('Hello World');
});


app.get('/:name', (req: Request, res: Response) => {
    res.send(`Hello ${req.param('name', 'Mark')}`);
});


app.listen(port, () => {
    console.log(`Server listening at port: ${port}`);
});
```

Before starting the debug server, place breakpoints anywhere in the __app.ts__ file and run the __npm start__ command to start the __TypeScript Compilation Server__ and then press __F5__ and open your browser and navigate to __http://localhost:3000__ or __http://localhost:3000/anna__. And, if it's working and it passes your breakpoints then great but if not then maybe there's something with your configurations, please follow the instructions above and retrace the things that you missed.


By the way, I haven't mentioned the most important thing that allows us to debug our TypeScript code. It's __Source Maps__. Most of our code (JS/CSS) in production are combined and minified so that we can dramatically reduce the size of our assets and also reduce the number of files in production to improve the load time performance of a website. But debugging in a minified code is hard, sorry "hard" is a soft word for this, it's impossible. This is where __Source Maps__ comes into play. Basically, a __Source map__ is a file that maps the minified/transformed source to the original source. This helps us, developers, a lot because we can debug that minified code with the original code. __Source maps__ are awesome.


##Thanks guys for reading this post.
# Have a Nice Day :smiley:!.