Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES2015 `import` alternative for `require()()`? [duplicate]

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?

like image 482
Stijn de Witt Avatar asked Apr 17 '26 12:04

Stijn de Witt


1 Answers

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');
like image 73
Dan Prince Avatar answered Apr 19 '26 00:04

Dan Prince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!