ES6 Destructuring and Module imports

时光怂恿深爱的人放手 提交于 2019-11-27 07:44:40
Felix Kling
import {Link} from 'react-router';

imports a named export from react-router, i.e. something like

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.

export default {
  Link: 42
};

(the default export is actually nothing but a standardized named export with the name "default").

See also export on 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.

To do this:

import {purple, grey} from 'themeColors';

Without repeating export const for each symbol, just do:

export const
  purple = '#BADA55',
  grey = '#l0l',
  gray = grey,
  default = 'this line actually causes an error';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!