- Learning JavaScript Data Structures and Algorithms
- Loiane Groner
- 193字
- 2021-08-27 18:41:11
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 run the node command, passing the --experimental-modules to it as in the following code:
cd 17-ES2015-Modules-node node --experimental-modules 17-ES2015-ES6-Modules.mjs
In the following screenshot, we can see the commands and the output:

At the time of writing this book, the target for Node.js to support ES2015 import feature is Node 10 LTS.