Shorter syntax for Node.js module import

I’ve found myself writing a lot of import module statements during React development that I could have shortened. It’s a bit dispiriting when everything above the fold in your code is a boilerplate import. To give an example – this very simple React page

(this demo app is so bland I actually tarted up the image in photoshop – and it’s still bland)

Is constructed from this component

Even in this simple example, I’ve a bunch of imports from the same Alerts module. This could potentially go on and on and has done when I’m using something like React-Bootstrap. It’s not pretty. Happily this can all be shortened to one line thus

When I first saw this I found it baffling and unexplained – especially when just importing 1 object from a module e.g.

Suddenly there is curly brackets in the way. What’s all that about?

It’s all in the Destructure

It’s using ES6 object destructuring to do this magic. A simple example of object destructuring would be

The first object is automatically split into 2 variable when assigned – this is the destructuring

So our react import is the same as this in essence. Label.jsx is the component (object) we are importing

The export at the end is what is going to be destructured – we could simplify this further and omit the property names (with more ES6)

Anyway that’s not strictly relevant. Explaining onwards – the require squirts out the object and the destructuring assigns it to 3 variables which we can use in our page

This can be rewritten as an ES6 import statement which will transpile down into require with something like Babel if need be.

It’s this form in particular I often see in code samples and the like. So that’s explained then and a little bit of the grey fog has lifted. Lovely.

Useful Links

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
ES6 Destructuring – good detailed explanation

https://blog.risingstack.com/node-js-at-scale-module-system-commonjs-require/
This is all underpinned by Node.js CommonJS module load pattern – that’s the require bit. More detail above.

https://github.com/timbrownls20/Demo/tree/master/React/CommonJSDemo
The sample code isn’t much but as ever the code is on my GitHub site. It’s using webpack as the task runner which is different to the gulp runner I’ve been using. Probably better if I’m honest.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *