Open In App

How to use EcmaScript modules in Node.js ?

Last Updated : 07 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

CommonJS modules consists usage of exports and require() statements, while EcmaScript modules consists usage of import and export statements.

Learn more here: Difference between node.js require and ES6 import and export

Node.js treats JS code as CommonJS modules by default, However the EcmaScript modules can be used instead of using –experimental-modules flag.

Follow the below mentioned Steps:

  • Initialize a package.json for Node.js project inside desired folder using following command, and enter values as prompted.

    npm init
  • Enter following command to skip prompts:

    npm init -y

  • Open newly created package.json and add following field.

    "type":"module"    

    Example:

  • File structure:

  • Example:

    area.js




    const areaOfRectangle = (length, breadth) => {
        return length * breadth
    }
        
    export default areaOfRectangle

    
    

    index.js




    import areaOfRectangle from './area.js'
      
    console.log('Area of rectangle: ', areaOfRectangle(5, 8))

    
    

Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads