Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to use an ES6 import in Node.js?

  • Difficulty Level : Expert
  • Last Updated : 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:

  1. Importing an entire module: 



    import * as name from 'module-name'
  2. Import default export from a module:

    import name from 'module-name'
  3. Importing a single export from a module:

    import { name } from 'module-name'
  4. Importing multiple exports from a module:

    import { nameOne , nameTwo } from 'module-name'
  5. 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.

    1. In the package.json file add “type” : “module”. Adding this enables ES6 modules.

      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"
      }
    2. 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.



    My Personal Notes arrow_drop_up
Recommended Articles
Page :