Open In App

How to export a single value or element in a Module ?

Improve
Improve
Like Article
Like
Save
Share
Report

Modules in JavaScript contain some data or functions which can be reused anywhere by calling them. The export statement is used while creating these modules so that, the same modules can be imported in any other part of code to use those data and perform some tasks(carried out by functions) repetitively.

Syntax: The following syntax is used to export the single value/element from the module

export default element;

Note: This syntax is only used for exporting a single value from the module, no other values can be exported if a default export is used as it is only one per module.

Project Structure: It will look like the following.

Project Structure of Code

Here, In the root folder of “GFG-MODULES” there are 3 files namely “index.html”,  “index.js” and our “package.json” file along with these, it has the “modules” folder containing a file named “siteData.js”.

Code Example : 

Step 1: Configuring package.json file so that it won’t cause any errors when export statements are used
In our package.json file, add the following property:

"type" : "module"

When you have the “type: module” property, then your source code can use the import syntax, otherwise, it will cause errors and will only support the “require” syntax. Your package.json file should look similar to this:

Javascript




{
  "name": "gfg-modules",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "GFG",
  "license": "ISC"
}


Step 2: Export the single element from the module. Here in the siteData.js  file, we have multiple elements but we are only exporting a single value from this module that is “siteName”.

Javascript




const siteName = "GeeksForGeeks";
const founderName = "Sandeep Jain";
const aboutSite = "A Computer Science portal for geeks";
const siteContent = "Computer science and Programming articles along with Courses";
export default siteName;


Step 3: Importing the single element in index.js. Here we have imported the single value which we have exported from the module “siteData.js”

Javascript




import siteName from "./modules/siteData.js";
  
console.log(siteName);


Step to run the application: Open the terminal and type the following command.

node index.js

Output: 

GeeksForGeeks


Last Updated : 14 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads