import and call a function with es6 [duplicate]

2019-01-25 04:16发布

问题:

This question already has an answer here:

  • Pass options to ES6 module imports 6 answers

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?

回答1:

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.



回答2:

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).



回答3:

import http from "debug"; // not sure if this is the desired effect