ES6 Style Module Imports Explained
In JavaScript it is often more clear to only import parts of modules/objects when they are needed. Before ES6 this was a cumbersome task which required assigning to multiple variables. For example, in Node.js:
const mod = require('./partialModuleImportsToRequire'); const property1 = mod.property1; const property2 = mod.property2; property1(); // Message for property1 property2(); // Message for property2
Here is partialModuleImportsToRequire.js:
module.exports = { property1: function() { console.log('Message for property1'); }, property2: function() { console.log('Message for property2'); }, doNotIncludeThis: 'doNotIncludeThis' };
With ES6, the import can be simplified as:
const { property1, property2 } = require('./partialModuleImportsToRequire'); property1(); // Message for property1 property2(); // Message for property2
Although this looks like a special import syntax, it actually is derived directly from two ES6 features; Destructuring Assignments and Shorthand Property Names. Firstly, Destructuring Assignments specify how to insert values from one data structure from another (both objects in this case). To visualize this better, I replaced the import with the object it returns:
const { property1: property1, property2: property2 } = { property1: function() { console.log('Message for property1'); }, property2: function() { console.log('Message for property2'); }, doNotIncludeThis: 'doNotIncludeThis' }
This says take the left property name property2, find it in the object on the right hand side, then assign it to a variable called property2. The right hand side name could be changed to assign property2 from the original object to a different property name.
Next, when two properties have the same name, a shorthand can be used so that only one of them has to be entered. Then if both properties are put on one line you get the original syntax:
const { property1, property2 } = ...
More information on Destructuring Assignments and Shorthand Properties.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/partialModuleImports.js





