ES2015 `import` alternative for `require()()`?

11,396

Solution 1

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');

Solution 2

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 { ... }
Share:
11,396
Stijn de Witt
Author by

Stijn de Witt

I'm a web developer with an interest in Java (EE), OSGi, PHP, HTML(5), CSS and Javascript. Currently I'm working on Bridal App, a platform for the bridal industry. My blog: Stijn de Witt's blog My Google+: +Stijn de Witt

Updated on June 07, 2022

Comments

  • Stijn de Witt
    Stijn de Witt almost 2 years

    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?