Supporting ES6 modules on older Node.js versions

Initially, ES6 module support was an experimental feature in Node.js 8.5 and became a fully supported feature in Node.js 14. With the right tools, we can use it on earlier Node.js implementations.

The better method of using ES6 modules on Node.js 6.x is the esm package. Simply do the following:

$ nvm install 6

Downloading and installing node v6.14.1…

Downloading

https://nodejs.org/dist/v6.14.1/node-v6.14.1-darwin-x64.tar.xz… ######################################################################

## 100.0%

Computing checksum with shasum -a 256 Checksums matched!

Now using node v6.14.1 (npm v3.10.10)

$ nvm use 6

Now using node v6.14.1 (npm v3.10.10)

$ npm install esm

… npm output

$ node –require esm simpledemo.mjs

Hello, world!

1 1
2 4
2 4
3 9
4 16
5 25
42

There are two ways to use this module:

  • In a CommonJS module, invoke require(‘esm’).
  • On the command line, use –require esm, as shown here.

In both cases, the effect is the same, to load the esm module. This module only needs to be loaded once, and we do not have to call any of its methods. Instead esm retrofits ES6 module support into the Node.js runtime, and is compatible with version 6.x and later.

So, we can use this module to retrofit ES6 module support; it does not retrofit other features such as async functions. Successfully executing the ls.mjs example requires support for both the async functions and arrow functions. Since Node.js 6.x does not support either, the ls.mjs example will load correctly, but will still fail because it uses other unsupported features.

$ node –version v6.14.1

$ node –require esm ls.mjs

/Users/David/chap03/ls.mjs:5

(async () => {

^

 SyntaxError: Unexpected token (

at exports.runInThisContext (vm.js:53:16)

at Module._compile (module.js:373:25)

 It is, of course, possible to use Babel in such cases to convert the full set of ES2015+ features to run on older Node.js releases.

In this section, we’ve learned about how to define a Node.js module and various ways to use both CommonJS and ES6 modules. But we’ve left out some very important things: what is the module identifier and all the ways to locate and use modules. In the next section, we cover these topics.

Source: Herron David (2020), Node.js Web Development: Server-side web development made easy with Node 14 using practical examples, Packt Publishing.

Leave a Reply

Your email address will not be published. Required fields are marked *