How to use an ES6 import in Node.js? - GeeksforGeeks

08 Feb, 2021
Introduction to ES6 import: 
The import statement is used to import modules that are exported by some other module. A module is a file that contains a piece of reusable code. The import modules are in strict mode whether it is declared or not.
Syntax of import:
import name from 'module-name'
Importing can be done in various ways:
Importing an entire module: import * as name from 'module-name'Import default export from a module:import name from 'module-name'Importing a single export from a module:import { name } from 'module-name'Importing multiple exports from a module:import { nameOne , nameTwo } from 'module-name'Importing a module for side effects onlyimport './module-name'Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "type": "module",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})Now run the index.js file by typing node –experimental-modules index.js in the terminal. Using the esm module:Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.Now, when using a file with .mjs extension the package.json file will look like this:JavascriptJavascript// package.json when using .mjs file{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}Create a file index.mjs and write the program using ES6 import.JavascriptJavascript//index.mjs  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.Using the esm moduleInstallationnpm install esmNow try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code//server.js
require = require("esm")(module);
module.exports = require("./index.js");Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. Now in the terminal type node server.js to execute the programThe output of the index.js and index.mjs file in the above method is:localhost:5000Advantages of using import in place of require in nodejs:Import helps in selectively loading the pieces of code which are required that helps in saving memory.In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.My Personal Notes
arrow_drop_upSave
Importing an entire module: import * as name from 'module-name'
Importing an entire module: 
import * as name from 'module-name'
Import default export from a module:import name from 'module-name'
Import default export from a module:
import name from 'module-name'
Importing a single export from a module:import { name } from 'module-name'
Importing a single export from a module:
import { name } from 'module-name'
Importing multiple exports from a module:import { nameOne , nameTwo } from 'module-name'
Importing multiple exports from a module:
import { nameOne , nameTwo } from 'module-name'
Importing a module for side effects onlyimport './module-name'Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "type": "module",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})Now run the index.js file by typing node –experimental-modules index.js in the terminal. Using the esm module:Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.Now, when using a file with .mjs extension the package.json file will look like this:JavascriptJavascript// package.json when using .mjs file{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}Create a file index.mjs and write the program using ES6 import.JavascriptJavascript//index.mjs  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.Using the esm moduleInstallationnpm install esmNow try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code//server.js
require = require("esm")(module);
module.exports = require("./index.js");Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. Now in the terminal type node server.js to execute the programThe output of the index.js and index.mjs file in the above method is:localhost:5000Advantages of using import in place of require in nodejs:Import helps in selectively loading the pieces of code which are required that helps in saving memory.In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.My Personal Notes
arrow_drop_upSave
Importing a module for side effects only
import './module-name'
Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:
Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.
In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "type": "module",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})
In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "type": "module",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}
The package.json file should look like this:
package.json
//package.json{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "type": "module",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}
Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})
Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js file
index.js file
//index.js  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})
Now run the index.js file by typing node –experimental-modules index.js in the terminal. 
Using the esm module:
Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.
Now, when using a file with .mjs extension the package.json file will look like this:
Javascript
// package.json when using .mjs file{  "name": "index",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC"}
Create a file index.mjs and write the program using ES6 import.
Javascript
//index.mjs  import express from 'express';  const app = express();  app.get('/',(req,res) => {    res.send('GeeksforGeeks');})  const PORT = 5000;  app.listen(PORT,() => {    console.log(`Running on PORT ${PORT}`);})
Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.
Using the esm module
Installation
npm install esm
Now try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. 
Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code
//server.js
require = require("esm")(module);
module.exports = require("./index.js");
Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. 
Now in the terminal type node server.js to execute the program
The output of the index.js and index.mjs file in the above method is:
localhost:5000
Advantages of using import in place of require in nodejs:
Import helps in selectively loading the pieces of code which are required that helps in saving memory.
In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
JWT Authentication with Node.js
Express.js req.params Property
How to build a basic CRUD app with Node.js and ReactJS ?
Installation of Node.js on Windows
How to Install a local module using npm?