Javascript 使用 es6 导入和调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31599566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
import and call a function with es6
提问by Mohamed El Mahallawy
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?
使用es6,如何像第一行一样立即导入和调用?
import debug from 'debug'();
is a no no?
是不是不是?
回答by loganfsmyth
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.
导入语法是声明性导入语法,它不执行任何函数。
回答by jmar777
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.
正确的。请记住,该import
语句不仅仅是一个简单的require()
语句——它还创建了“加载”模块与局部变量的绑定。
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).
与 commonjs 风格的模块加载器的类比在某些时候显然会崩溃,但归根结底,这是一个“不,不”,因为简单明了的事实实际上import debug from 'debug'
并没有解析为您可以调用的任何内容(或以其他方式)参考)。
回答by Vidul
import http from "debug"; // not sure if this is the desired effect