Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import part of object in ES6 modules

Tags:

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.

like image 992
Glen Swift Avatar asked May 08 '15 10:05

Glen Swift


People also ask

How can I conditionally import an ES6 module?

To conditionally import an ES6 module with JavaScript, we can use the import function. const myModule = await import(moduleName); in an async function to call import with the moduleName string to import the module named moduleName . And then we get the module returned by the promise returned by import with await .

How many parts are there in an ES6 module?

The ES6 module standard has two parts: Declarative syntax (for importing and exporting) Programmatic loader API: to configure how modules are loaded and to conditionally load modules.

Can I use ES6 imports?

Importing can be done in various ways:Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.

How does ES6 import export work?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.


1 Answers

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; 
like image 51
just-boris Avatar answered Sep 16 '22 13:09

just-boris