Using native ES2015 imports in Node.js

It would be nice if we could use the ES2015 imports in Node.js so that we don't need to transpile our code. Starting with Node 8.5, we can use ES2015 imports in Node.js as an experimental feature.

For this example, we will create a new folder inside chapter01 called 17-ES2015-Modules-node. We will copy the files 17-CalcArea.js, 17-Book.js, and 17-ES2015-ES6-Modules.js to this folder and we will change the extension from js to mjs (the .mjs extension is a requirement so that this can work). In the 17-ES2015-ES6-Modules.mjs file, we will update the imports, adding the .mjs extension to it as follows:

import * as area from './17-CalcArea.mjs'; 
import Book from './17-Book.mjs'; 

To execute the code, we will ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.