Declarative “import” in ES6

This post is about coding styles. We talk a lot about functional and declarative programming so it’s time to look into LISP-like syntax but with less parenthesis (a.k.a. in JavaScript)

We can import a module as a whole:

import obj1 from 'module';

And then, if the module with multiple exports, we can refer to one of them:

const a1 = obj1.some();

However, we can use ES6 object destructuring to import only that sub-object:

import { some } from 'module';
const a1 = some();

However, what happen if we want to import more objects from a single module. For example:

import { FETCH_MESSAGES_FETCHING, FETCH_MESSAGES_SUCCESS, FETCH_MESSAGES_FAILURE,} from ‘actions’;

(Yes, this is very a common import sentence pattern in Redux, specially when doing some asynchronous flow)

So, at this point I have two ways to solve this:

  1. Avoid using object destructuring. This means write “actions” everywhere the objects apeear.
  2. Multiline imports.

I am not going to debate what option to choose. This post is just suggesting a coding style if you choose 2.

These are my options for that

K&R vs Lisp

Let’s compare both styles:

  • Option 1 is more legible
  • Option 1 is more git-friendly
  • Option 1 has consistent indentation (line 10 has 9 spaces for indentation?!)
  • Option 2 occupies less space

Cleary the winner is option 1. But what happens when there are more imports:

Here I am not sure if option 1 is still the winner:

  • Option 1 is still more beautiful
  • Option 2 has all the imports aligned and all the sources (the module name) too.

I prefer the second one, which is less beautiful but more clean.