Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - How to import part of object in ES6 modules

In the react documentation I found this way to import PureRenderMixin

var PureRenderMixin = require('react/addons').addons.PureRenderMixin;

How can it be rewritten in ES6 style. The only thing I can do is:

import addons from "react/addons";
let PureRenderMixin = addons.addons.PureRenderMixin;

I hope there is a better way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately import statements does 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:

 //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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...