3

Some Node JS libraries (e.g. debug) use this pattern with require statements:

var debug = require('debug')('http');

This is basically a require of a function which is then directly invoked.

My question: Is there a similar construct using ES2015 import statements?

How would you translate such code if you were converting from commonjs to es2015 syntax?

Stijn de Witt
  • 40,192
  • 13
  • 79
  • 80
  • 1
    Interestingly, I just received a 'Famous Question' badge for this question because it was viewed over 10.000 times... Still it was closed as being a duplicate :( – Stijn de Witt Aug 17 '21 at 08:37

2 Answers2

6

That pattern only works because require(debug) returns a value that can be used immediately.

var debug = require('debug')('http');

import is a bit like if in the sense that it doesn't resolve as a value.

var d = if(a) { b } else { c }; // unexpected token
var debug = import debug from 'debug'; // unexpected token

require shares semantics with the ? operator which performs the same function as if, but resolves as a value.

var d = a ? b : c;
var debug = require('debug');

The only option is to split the statement up.

import _debug from 'debug';
var debug = _debug('http');
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
1

There is no such shorthand in ES2015.

You would just have to split the code into two parts:

import _debug from 'debug';
const debug = _debug('http');

For which the export would be:

export default function { ... }
nils
  • 25,734
  • 5
  • 70
  • 79