33

Previously:

var debug = require('debug')('http')
  , http = require('http')
  , name = 'My App';

With es6, how can I import and invoke right away like the first line?

import debug from 'debug'();

is a no no?

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84

3 Answers3

49

You'll need two lines:

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

The import syntax is a declarative import syntax, it does not execute any functions.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 5
    The problem is that sometimes you need to call the function before any other import statements. `import` does not allow the execution of other statements before all `import` statements are declared. – user2078023 Apr 10 '19 at 11:32
  • @user2078023 In that case it may be best to move the whole import-and-call into a separate module, which you can import when you need both to happen. – JW. Apr 25 '23 at 02:02
4

is a no no?

Correct. Keep in mind that the import statement is analogous to more than a simple require() statement -- it also creates a binding of the "loaded" module to a local variable.

That is,

import debug from 'debug'();

...is more close in behavior/semantics to

var debug = require('debug');

...than it is to simply

require('debug');

Analogies to commonjs-style module loaders will obviously break down at some point, but at the end of the day it's a "no no" due to the plain and simple fact that import debug from 'debug' doesn't actually resolve to anything that you can invoke (or otherwise reference).

jmar777
  • 38,796
  • 11
  • 66
  • 64
-21
import http from "debug"; // not sure if this is the desired effect
Vidul
  • 10,128
  • 2
  • 18
  • 20