Two ES6 features that help with CommonJS modules

[2017-03-26] dev, javascript, esnext, commonjs, nodejs
(Ad, please don’t block)

Even without ES modules, ES6 is a joy to use in Node.js. Two ES6 features eliminate some of the redundancy of CommonJS syntax.

Importing and destructuring  

Destructuring can make importing more concise.

Without destructuring:

const func = require('lib').func;

With destructuring:

const {func} = require('lib');

Exporting and property value shorthands  

Exporting can profit from property value shorthands.

Without property value shorthands:

function foo() { ··· }
function bar() { ··· }
function baz() { ··· }

module.exports = {
    foo: foo,
    bar: bar,
    baz: baz,
};

Using property value shorthands:

function foo() { ··· }
function bar() { ··· }
function baz() { ··· }

module.exports = { foo, bar, baz };

Over the years, I’ve tried various other ways of being less redundant when exporting, but this approach seems cleanest to me.

Further reading