Sunday, 2 March 2025

How export default Simplifies JavaScript Modules?

In JavaScript, export default is used to export a single value, function, or class from a module. It allows the module to export one primary item that can be imported without specifying a name.

Syntax 

export default value;

circle-util.js

export default function areaOfCircle(radius){
    if (typeof radius !== 'number'){
        throw new Error("radius is not a number");
    }
    return 3.14 * radius * radius;
}

default-export.js

import circleArea from "./circle-util.js"

console.log(`Area of Circle for the radius 5 is ${circleArea(5)}`);

Output

Area of Circle for the radius 5 is 78.5

How to rersolve the error “Cannot use import statement outside a module”?

The error Cannot use import statement outside a module occurs in Node.js because Node.js uses CommonJS module system by default, whereas import and export syntax is part of ECMAScript (ES) modules.

 

To resolve this error, set "type": "module" in package.json.

 

package.json

{
  "name": "your-app",
  "version": "1.0.0",
  "type": "module"
}

 

"type": "module" in your package.json file indicates that all .js files in your project are treated as ES modules.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment