How to use the "debug" module with typescript

27.9k views Asked by At

I have an NTVS (Node Tools for Visual Studio) project with Typescript.
The following statement doesn't compile:

import debug = require('debug')('MyApp');

The syntax error being

(TS) ';' expected

between the the two parenthesis ')('
Is it possible to use "debug" with TypeScript?

3

There are 3 answers

4
Scott Byers On

The answers here did not work for me with more recent versions of Typescript. Here's how I got it working with proper import syntax in Typescript ^3.5.3:

Install Debug package and Typescript types for Debug (types only needed for dev)

npm install --save debug
npm install --save-dev @types/debug

Then in .ts files:

import Debug from "debug";
const debug = Debug("AppName");

Hope this helps someone else!

1
spechter On

Remember that TypeScript is a super-set of javascript, so you can still also do this one-liner:

const debug = require('debug')('my-app:my-module');

Typescript seems to conclude that the debug constant here is of type 'any', and you lose all type safety, but with a package as simple as debug is, I think you will be OK...

Personally, I think 2 lines to instantiate debugging in every module is 1 line too many, so I continue to use this one-liner in my .ts files.

P.S. I like to use module tags so I can enable logging in just certain modules with DEBUG=my-app:my-module,my-app:some-other-module ts-node my-app or all my modules with DEBUG=my-app:* ...

3
bjacobowski On

From the README, debug module is exporting a function that decorates console.error with your module name (MyApp). I'm guessing there are other ways, but I use:

import Debug from "debug";
const debug = Debug("MyApp");

// then to use
debug("Something happened");

And to print everything to the console, run your app with...

$ DEBUG=* node MyApp.js