debug icon indicating copy to clipboard operation
debug copied to clipboard

Specify namespace with url in ESM

Open sebamarynissen opened this issue 2 years ago • 8 comments

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

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

and we have to do

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

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

// 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

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:

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.

sebamarynissen avatar Oct 19 '23 10:10 sebamarynissen

A workaround you can use is createRequire

import { createRequire } from 'node:module';

const newRequire = createRequire(import.meta.url);
const debug('namespace');

bryanjtc avatar Nov 01 '23 07:11 bryanjtc

@bryanjtc That would be kind of pointless because the entire goal is to make it a one-liner again.

Anyway, I've decided to create my own npm module debug-ns for it. I would be happy to eventually merge it in the debug module and then mark my debug-ns as deprecated.

sebamarynissen avatar Nov 01 '23 10:11 sebamarynissen

This actually isn't the worst idea. To be completely honest I didn't know this was possible.

Right now the V5 roadmap is blocked (still) on some Node things, but it'd be nice to have this eventually.

Qix- avatar Nov 01 '23 11:11 Qix-

@Qix- Cool, I'll try to file a PR for this soon

sebamarynissen avatar Nov 01 '23 13:11 sebamarynissen

@sebamarynissen you could do this in one line:

const debug = (await import("debug")).default("namespace");

yetzt avatar Mar 01 '24 23:03 yetzt