Javascript ES6 解构和模块导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33524696/
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
ES6 Destructuring and Module imports
提问by Guy
I was under the impression that this syntax:
我的印象是这种语法:
import Router from 'react-router';
var {Link} = Router;
has the same final result as this:
具有与此相同的最终结果:
import {Link} from 'react-router';
Can someone explain what the difference is?
有人可以解释一下有什么区别吗?
(I originally thought it was a React Router Bug.)
(我原本以为是React Router Bug。)
回答by Felix Kling
import {Link} from 'react-router';
imports a named exportfrom react-router
, i.e. something like
从导入一个命名的导出react-router
,即类似的东西
export const Link = 42;
import Router from 'react-router';
const {Link} = Router;
pulls out the property Link
from the default export, assuming it is an object, e.g.
Link
从默认导出中提取属性,假设它是一个对象,例如
export default {
Link: 42
};
(the default export is actually nothing but a standardized named export with the name "default").
(默认导出实际上只是一个名为“default”的标准化命名导出)。
See also export
on MDN.
另请参见export
MDN。
Complete example:
完整示例:
// react-router.js
export const Link = 42;
export default {
Link: 21,
};
// something.js
import {Link} from './react-router';
import Router from './react-router';
const {Link: Link2} = Router;
console.log(Link); // 42
console.log(Link2); // 21
With Babel 5 and below I believe they have been interchangeable because of the way ES6 modules have been transpiled to CommonJS. But those are two different constructs as far as the language goes.
在 Babel 5 及以下版本中,我相信它们是可以互换的,因为 ES6 模块已被转换为 CommonJS。但就语言而言,这是两种不同的结构。
回答by Devin G Rhode
To do this:
去做这个:
import {purple, grey} from 'themeColors';
Without repeating export const
for each symbol, just do:
无需export const
为每个符号重复,只需执行以下操作:
export const
purple = '#BADA55',
grey = '#l0l',
gray = grey,
default = 'this line actually causes an error';