Import/Export Business — A JavaScript journey #6



Feb 25th 2019 in Développement web

Do you like to organize your JavaScript projects in multiple and ingeniously split code files, me too! Lucky you (and me), thanks to Webpack or any tool of this kind, it's getting simpler and simpler, especially with the export / import statements. But when and how do I use them?


With the ECMAScript 2015 blessing, came the import and export statements, also known as JavaScript modules or ES modules. Very flexible and easy to use, It's sadly not yet supported on every browser (no shit Sherlock), but also not entirely on NodeJS.

Node was using CommonJS for a long time, but they are working on a Modules Implementation to stay close to the browser implementation. For the moment, it's more stable and safe to use module.exports and require() on your Node applications, but if you want to follow the progress of the Module Team, I invite you to read the very clear blog post of Dr. Axel Rauschmayer or to check the official Github repository.


The most basic form is when you want to export by default a variable that you've created and use it in another file.

You can also directly export without the need of creating a variable.

Now, you oftently need to export and import more than one variable, for that you can do something like this :

As you can see, no more default export and now, you can import whatever method you want to use elsewhere.

More advanced

You can also combine targeted variables and default export when importing.

When names are not well suited for some cases, you can rename it during export and/or import!

If there is multiple export, but you want to attach them all to a single item, you can import *

Expert mode

When your multiple export module start to (re-)create some kind of monolithic file, it's time to use an export proxy.


As you can see, it's a pretty simple topic, but very useful, especially to keep your projects organized and easy to understand. CommonJS was a good start, but import/export statements are really the apotheosis of JavaScript modules management and God, it's so pleasing to write something like import React, { useState } from 'react'; :heart_eyes: