使用ES6导入并调用函数

33

之前:

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

使用 ES6,我该如何像第一行那样导入并立即调用?

import debug from 'debug'();

是个不行的选择吗?

3个回答

49

你需要两行:

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

导入语法是一种声明性的导入语法,它不执行任何函数。


5
问题在于有时你需要在任何其他导入语句之前调用该函数。 import 不允许在声明所有 import 语句之前执行其他语句。 - user2078023
在这种情况下,最好将整个导入和调用移动到一个单独的模块中,当您需要同时发生两者时,可以进行导入。 - JW.

4

是个不行的选择吗?

正确。请记住,import语句不仅仅类似于一个简单的require()语句——它还创建了将“加载”的模块绑定到本地变量的绑定。

也就是说,

import debug from 'debug'();

...更接近于行为/语义

var debug = require('debug');

比起简单地

...

,使用...更容易
require('debug');

显然,与CommonJS模块加载器的类比会有所不同,但归根结底,这是一个“不行”的问题,因为import debug from 'debug'实际上无法解析为任何可以调用(或引用)的内容。


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

15
请确保,这并没有产生预期的效果。 - maxkoryukov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接