Using ES6 And Node.js, Recommended Way To Require

- 1 answer

Using ES6, and Node.js, what is the recommend way to require packages let or const?

let _ = require('underscore');


const _ = require('underscore');


Unless you plan on ever redefining the package within the scope of your file (or wherever you're requireing) then it's probably best to use const: This will protect against accidental reassignments of the package variable.

For instance:

const _ = require('underscore');
// ...
let [a, _] = foo;  // SyntaxError: "_" is read-only

Since we're talking about ES6, const, and require, it makes sense to bring up import statements as well, which for the most part can be thought of as a more flexible version of require. [1]

import _ from 'underscore';
// ...
let [a, _] = foo;  // TypeError: duplicate declaration "_"

ES6 imports register as const by default, thus similarly preventing reassignment.

So, when would you want to use let for a require? Let's say (no pun intended) you want to use a special version of a package in certain environments.

let secureLibrary = require('secureLibrary');
// override all security in dev mode
if (process.env['NODE_ENV'] === 'development') {
    secureLibrary = secureLibrary.fake;

In this contrived example, during development, your use of secureLibrary will be replaced by a fake one, presumably ignoring self-signed SSL certificates or some other convenience that would be unsuitable for production.

In summary: most of the time use const but occasionally let provides necessary flexibility, and consider using import if you're already using ES6!

[1] Please note: under the hood there are many more differences between ES6 import and CommonJS require, please see Using Node.js require vs. ES6 import/export and for many more gory details.