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 esmExample:
function add(a,b){
return a+b;
}
export default add;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.jsOutput:
3Similarly, 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.
{
"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

