javascript 在 ES6 中使用密钥导入需要如何更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31780616/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:22:49  来源:igfitidea点击:

How change require to import with key in ES6?

javascriptecmascript-6babeljs

提问by godban

I want to write require with ES6 import. In the case without a key, it is pretty easy to do:

我想用 ES6 导入编写 require。在没有钥匙的情况下,很容易做到:

var args2 = require('yargs2');-> import foo from 'bar';

var args2 = require('yargs2');-> import foo from 'bar';

But with a key, I can't find the appropriate syntax:

但是用一个键,我找不到合适的语法:

var foo = require('bar').key;

How can I do that?

我怎样才能做到这一点?

回答by lyschoening

The syntax for importing a member of a module with an aliased name is:

导入具有别名的模块成员的语法是:

import {key as foo} from 'bar';

This is equivalent to var foo = require('bar').key;

这相当于 var foo = require('bar').key;

If you want to import a member without aliasing it, the syntax is simpler:

如果要导入成员而不为其添加别名,则语法更简单:

import {foo} from 'bar';

Is equivalent to:

相当于:

 var foo = require('bar').foo;

MDN article about the import statement

关于导入语句的 MDN 文章

回答by Amit

var foo = require('bar').keyis identical to var bar = require('bar'); var foo = bar.key(other then the declaration of a 'bar' variable that is probably no longer needed).

var foo = require('bar').keyvar bar = require('bar'); var foo = bar.key(除了可能不再需要的“bar”变量的声明)相同。

if you export an object that has a property named 'key', that would be the same in ES6 import/export.

如果导出具有名为“key”的属性的对象,则在 ES6 导入/导出中也是如此。

import bar from 'bar';
var foo = bar.key;

NoteThis assumes a default export (export default xxx) as in OP. If using a named export (export foo), the syntax to use is import {foo} from 'bar'

注意这假定默认导出 (export default xxx) 就像在 OP 中一样。如果使用命名导出 (export foo),则使用的语法是import {foo} from 'bar'