Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “Exploring ES6”
Book, exercises, quizzes
(free to read online)
Logo of newsletter “ES.next news”
Newsletter (free)
Cover of book “JavaScript for impatient programmers”
Book (free online)

Two ES6 features that help with CommonJS modules

(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