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

Last Updated : 09 Sep, 2024

Summarize

Comments

Improve

ES6 or ECMAScript 2015 is the 6th edition of the ECMAScript language specification standard. It defines the standard on how to implement JavaScript.

ES6 introduced a standardized syntax for importing and exporting modules in JavaScript which we will cover in this guide.

The import statement is used to import modules 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:

import name from 'module-name';

Below are two approaches to use the ES6 import in NodeJS:

Different Ways to Use ES6 Import in JavaScript

Here we have covered all possible cases for using ES6 import statements in Node.js

Import OperationSyntax
Import entire moduleimport * as name from ‘module-name’
Import default export from a moduleimport name from ‘module-name’
Import single export from a moduleimport { name } from ‘module-name’
Import multiple exports from a moduleimport { nameOne , nameTwo } from ‘module-name’
Import 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:

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

To handle this issue, we use ES6 import. Let’s see how to use ES6 import in Node.js with examples.

Node.js has experimental support for ES modules. There are two methods to use ES6 import statement in Node.js. We two methods given below

Approach 1: By changing content of package.json file

To enable the use of ES6, we need to make some changes to the package.json file. Before following the steps make sure that Node.js is installed.

To use ES6 imports in Node.js,

  • set "type": "module" in your package.json file.
  • Use the import statement to include modules, ensuring file extensions like .js are explicitly specified.

Adding this enables ES6 modules. The package.json file should look like this:

//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", "dependencies": { "express": "^4.17.1" }}

Example: Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js file

JavaScript
//index.jsimport 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.

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

Output:

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

localhost:5000

Approach 2: By using the esm module

We can also enable ES6 import by installing esm module.

Step to install esm: write the following command

npm install esm

For Node versions older than 12: 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.

For newer node versions we can directly write node index.mjs to execute the task.

Now, when using a file with .mjs extension the package.json file will look like this:

// 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", "dependencies": { "esm": "^3.2.25", "express": "^4.17.1" }}

Example: Create a file index.mjs and write the program using ES6 import.

JavaScript
//index.mjsimport 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}`);})

Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed.

node index.mjs

Output:

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

localhost:5000

Advantages of using import in place of require in Node

  • Import helps in selectively loading the pieces of code that are required which helps in saving memory.
  • In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.

Conclusion

ES6 or ECMAScript 6 is designed for JavaScript language standardization. Using import statements in Node.js would earlier give an error, but after enabling ES6, we can easily use import statements in Node.js.

This tutorial, explains how to use ES6 import in Node.js. We have explained 2 ways to use import in Node.js with examples. Now easily import and export modules between files.



P

pritishnagpal

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

Improve

Next Article

Import and Export in Node.js

Please Login to comment...

How to use an ES6 import in Node.js? - GeeksforGeeks (2024)
Top Articles
Cost of living in Sweden – Routes North
Package Acceptance Pending: What It Means & What To Do
Section 4Rs Dodger Stadium
Kansas City Kansas Public Schools Educational Audiology Externship in Kansas City, KS for KCK public Schools
Terrorist Usually Avoid Tourist Locations
Tabc On The Fly Final Exam Answers
Top Financial Advisors in the U.S.
Retro Ride Teardrop
Flights to Miami (MIA)
Wal-Mart 140 Supercenter Products
CA Kapil 🇦🇪 Talreja Dubai on LinkedIn: #businessethics #audit #pwc #evergrande #talrejaandtalreja #businesssetup…
Baseball-Reference Com
The Blind Showtimes Near Showcase Cinemas Springdale
Hmr Properties
Med First James City
I Wanna Dance with Somebody : séances à Paris et en Île-de-France - L'Officiel des spectacles
Guilford County | NCpedia
2 Corinthians 6 Nlt
Wicked Local Plymouth Police Log 2022
Vistatech Quadcopter Drone With Camera Reviews
Voy Boards Miss America
U Arizona Phonebook
Keurig Refillable Pods Walmart
Cbssports Rankings
A Person That Creates Movie Basis Figgerits
Craigslist Apartments Baltimore
TeamNet | Agilio Software
Bra Size Calculator & Conversion Chart: Measure Bust & Convert Sizes
Wku Lpn To Rn
John Philip Sousa Foundation
Ncal Kaiser Online Pay
Hannah Jewell
Duke Energy Anderson Operations Center
Landing Page Winn Dixie
Gideon Nicole Riddley Read Online Free
Gabrielle Enright Weight Loss
404-459-1280
Tendermeetup Login
Sunrise Garden Beach Resort - Select Hurghada günstig buchen | billareisen.at
Sabrina Scharf Net Worth
Clausen's Car Wash
Emily Browning Fansite
N33.Ultipro
Gt500 Forums
The Blackening Showtimes Near Ncg Cinema - Grand Blanc Trillium
Kate Spade Outlet Altoona
Gander Mountain Mastercard Login
The top 10 takeaways from the Harris-Trump presidential debate
Smoke From Street Outlaws Net Worth
Morbid Ash And Annie Drew
Festival Gas Rewards Log In
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 5986

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.