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
What is an Open Port? - zenarmor.com
Breadcrumb Navigation for Websites: What It Is & How to Use It
Directions To Franklin Mills Mall
Google Sites Classroom 6X
What are Dietary Reference Intakes?
Umn Pay Calendar
Bhad Bhabie Shares Footage Of Her Child's Father Beating Her Up, Wants Him To 'Get Help'
Mikayla Campino Video Twitter: Unveiling the Viral Sensation and Its Impact on Social Media
Texas (TX) Powerball - Winning Numbers & Results
A.e.a.o.n.m.s
Craigslist Blackshear Ga
Check From Po Box 1111 Charlotte Nc 28201
Gayla Glenn Harris County Texas Update
Ratchet & Clank Future: Tools of Destruction
Craigslist Pet Phoenix
I Saysopensesame
Amortization Calculator
Vegas7Games.com
Universal Stone Llc - Slab Warehouse & Fabrication
Chaos Space Marines Codex 9Th Edition Pdf
Play Tetris Mind Bender
Violent Night Showtimes Near Amc Dine-In Menlo Park 12
480-467-2273
Marilyn Seipt Obituary
Danielle Moodie-Mills Net Worth
Roseann Marie Messina · 15800 Detroit Ave, Suite D, Lakewood, OH 44107-3748 · Lay Midwife
CohhCarnage - Twitch Streamer Profile & Bio - TopTwitchStreamers
Taylored Services Hardeeville Sc
Mobile crane from the Netherlands, used mobile crane for sale from the Netherlands
FSA Award Package
Guide to Cost-Benefit Analysis of Investment Projects Economic appraisal tool for Cohesion Policy 2014-2020
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Garrison Blacksmith's Bench
Breckie Hill Fapello
Appraisalport Com Dashboard /# Orders
Flashscore.com Live Football Scores Livescore
The Bold And The Beautiful Recaps Soap Central
Hannibal Mo Craigslist Pets
The Syracuse Journal-Democrat from Syracuse, Nebraska
Body Surface Area (BSA) Calculator
Tyler Perry Marriage Counselor Play 123Movies
St Anthony Hospital Crown Point Visiting Hours
Gopher Hockey Forum
13 Fun & Best Things to Do in Hurricane, Utah
4k Movie, Streaming, Blu-Ray Disc, and Home Theater Product Reviews & News
Scythe Banned Combos
Gt500 Forums
Euro area international trade in goods surplus €21.2 bn
Is My Sister Toxic Quiz
What Is The Gcf Of 44J5K4 And 121J2K6
Famous Dave's BBQ Catering, BBQ Catering Packages, Handcrafted Catering, Famous Dave's | Famous Dave's BBQ Restaurant
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.