node: creating a debugger setup for visual studio code and mochajs for typescript tests

The title of the post says everything that I wanted to say. I have been looking at how to create a more streamlined environment for my nodejs typescript development.
I was specifically interested in how to start only a specific test with the interactive debugger. I did not want to change the launch config every time I worked on a new test and I also wanted to handle mocha test  written in typescript.

I normally have a tsc process started in separate command window running tsc -w command.This watches all files and compiles when needed.

Here are the changes I made to Visual Studio Code and my environment.
In my project I installed:

  • typescript
  • mocha
  • mocha-typescript

I decided to hide all TypeScript generated files via adding a files.exclude directive to my USER SETTING  (access via File:Preferences:Settings), like so:

“files.exclude”: {
“**/.git”: true,
“**/.svn”: true,
“**/.hg”: true,
“**/CVS”: true,
“**/.DS_Store”: true,
“**/*.js.map”: true,
“**/*.js”: { “when”: “$(basename).ts”}
}

Then came the harder part. Finding a launch.config elements that would work (access via Debug:Open Configurations). I wanted to be able to open the debug pane and open the typescript test file I was working on, set breakpoints and click on “Start Debugging” button (green play button) and have the process kick off correctly.

This was not as trivial as I initially envisioned and much googling and blog reading ensued.
Here is the launch.config segment that worked for me.


{
“type”: “node”,
“request”: “launch”,
“name”: “Debug TS mocha”,
“program”: “${workspaceRoot}/node_modules/mocha/bin/_mocha”,
“stopOnEntry”: false,
“args”: [“${fileBasenameNoExtension}.js”,”–no-timeouts”, “–trace-warnings”,”–colors”],
“cwd”: “${fileDirname}”,
“sourceMaps”: true,
“outFiles”: [],
“env”: { “NODE_ENV”: “testing”}
}

This works well with standard mocha js test as well as typescript test files. For typescript you need to either have a watcher going or add a preprocess to the launch.config that transpiles your typescript first.

Hope this will save someone the head scratching I went though.

Cheers,
B.