javascript 如何在 ES6 模块中导入部分对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30121801/
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
How to import part of object in ES6 modules
提问by Glen Swift
In the react documentationI found this way to import PureRenderMixin
在反应文档中,我找到了这种导入 PureRenderMixin 的方式
var PureRenderMixin = require('react/addons').addons.PureRenderMixin;
How can it be rewritten in ES6 style. The only thing I can do is:
如何用 ES6 风格重写它。我唯一能做的就是:
import addons from "react/addons";
let PureRenderMixin = addons.addons.PureRenderMixin;
I hope there is a better way.
我希望有更好的方法。
回答by just-boris
Unfortunately import statementsdoes not work like object destructuring. Curly braces here mean that you want to import token with this name but not property of default export. Look at this pairs of import/export:
不幸的是import 语句不像对象解构那样工作。这里的花括号意味着您要导入具有此名称的令牌,但不是默认导出的属性。看看这对导入/导出:
//module.js
export default 'A';
export var B = 'B';
//script.js
import A from './a.js'; //import value on default export
import {B} from './a.js'; // import value by its name
console.log(A, B); // 'A', 'B'
For your case you can import whole object and make a destructuring assignment
对于您的情况,您可以导入整个对象并进行解构赋值
import addons from "react/addons";
let {addons: {PureRenderMixin}} = addons;