How to use the "debug" module with typescript
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 usedebug("Something happened");
And to print everything to the console, run your app with...
$ DEBUG=* node MyApp.js
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 debugnpm install --save-dev @types/debug
Then in .ts
files:
import Debug from "debug";const debug = Debug("AppName");
Hope this helps someone else!
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:* ...