#948·debug

Specify namespace with url in ESM

Author: sebamarynissenCreated Oct 19, 2023Updated Oct 14, 2025
Labelsfeaturechange-minor

When using native esm in Node, it's not possible anymore to use the pattern

javascript
const debug = require('debug')('namespace');

and we have to do

javascript
import createDebug from 'debug';
const debug = createDebug('namespace');

instead. In one of my projects, I've found myself to use an alternative approach though, where I do something like

javascript
import createDebug from 'debug';
const url = new URL(import.meta.url);
const [[namespace]] = url.searchParams;
export default createDebug(namespace);

so that it becomes possible to do stuff like

javascript
// In server
import debug from './debug.js?server';

// In worker
import debug from './debug.js?worker';

I was wondering whether it would be useful to have this functionality in the library itself. I'd be happy to clean my code up a bit and file a PR for this. An alternative approach would be to create my own npm module on top of the debug module if it's not desirable to have this in the library itself.

For the syntax, I was thinking about something like

javascript
import debug from 'debug/url?namespace'

where debug/url can become an exports in the package.json.

The url approach can be used to add more functionality as well, for example to force a specific color or something:

javascript
import createDebug from 'debug';
const url = new URL(import.meta.url);
const [namespace] = [...url.searchParams].find(([key, value]) => value === '');
const debug = createDebug(namespace);
const color = url.searchParams.get('color');
if (color !== null) {
  debug.color = color;
}
export default debug;

I'd love to hear some thoughts about this from the maintainers.