Skip to content

Specify namespace with url in ESM #948

Open
@sebamarynissen

Description

@sebamarynissen

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    change-minorThis proposes or provides a change that requires a minor releasefeatureThis proposes or provides a feature or enhancement

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions