import and call a function with es6 [duplicate]

2019-01-25 03:55发布

This question already has an answer here:

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?

3条回答
贼婆χ
2楼-- · 2019-01-25 04:11

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.

查看更多
Lonely孤独者°
3楼-- · 2019-01-25 04:15
import http from "debug"; // not sure if this is the desired effect
查看更多
在下西门庆
4楼-- · 2019-01-25 04:28

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

查看更多
登录 后发表回答