Search code examples
javascriptecmascript-6commonjs

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


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?


Solution

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