ES6 解构和模块导入 [英] ES6 Destructuring and Module imports
问题描述
我的印象是这种语法:
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?
(我原本以为这是一个 React Router Bug.)>
(I originally thought it was a React Router Bug.)
推荐答案
import {Link} from 'react-router';
从 react-router
导入一个 named export,例如
imports a named export from react-router
, i.e. something like
export const Link = 42;
<小时>
import Router from 'react-router';
const {Link} = Router;
从默认导出中取出属性Link
,假设它是一个对象,例如
pulls out the property Link
from the default export, assuming it is an object, e.g.
export default {
Link: 42
};
(默认导出实际上只是一个名为default"的标准化命名导出).
(the default export is actually nothing but a standardized named export with the name "default").
另请参阅 MDN 上的 export
.
See also export
on MDN.
完整示例:
// 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
<小时>
在 Babel 5 及以下版本中,我相信它们是可以互换的,因为 ES6 模块已被转换为 CommonJS.但就语言而言,这是两种不同的结构.
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.
这篇关于ES6 解构和模块导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!