Skip to content
Related Articles

Related Articles

How to use EcmaScript modules in NodeJS ?
  • Last Updated : 18 Feb, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :