by Sai gowtham

How to use es6 import statements in Node.js

In this tutorial, we are going to learn about how to use the es6 import and export statements in the Node.js.

Using the esm module loader

The esm module loader helps us to use the es6 imports in node.js instead of commonjs require() function and module.exports.

To use the esm module loader, first we need to install it from the npm by running the following command in your terminal.

npm install esm

Example:

add.js
function add(a,b){
    return a+b;
}

export default add;
app.js
import add from "./add"

console.log(add(1,2));

Now, you need to run the app.js file by adding -r esm flag after the node command.

node -r esm app.js

Output:

3

Similarly, if you are using node.js version >=13 it has a experimental support to the es6 modules.

To enable it, add the "type":"module" to the package.json file.

package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "description": "",
  "type": "module",  "scripts": {
    "start": "node app.js"
  }
}

for node versions 8-12, you can enable it by passing --experimental-modules to the node command and save the file extensions with .mjs instead of .js.

node --experimental-modules app.mjs

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course