Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptHow to import all exports of a file as an object in...

How to import all exports of a file as an object in Node.js ?

The import keyword is used in Javascript to use the elements that are exported from other modules. The syntax for importing all exports of a file as an object is as follows.

Syntax:

import * as objName from "abc-module"
...
let element1 = objName.value1

Here, objName is any name you give while first initializing the object when you import everything from the module into it.

Firstly 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:

{
   "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"
}

Project Structure :

Project Structure

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”.

Example: In siteData.js we have the following code:

siteData.js




export const siteName = "GeeksForGeeks";
export const url = "https://www.geeksforgeeks.org/";
export const founderName = "Sandeep Jain";
export const aboutSite = "A Computer Science portal for neveropen";
export let siteContent =
    "Computer science and Programming articles along with Courses";


Here in this file, we have exported multiple elements from our module “siteName”:

index.js




import * as site from "./modules/siteData.js";
  
console.log(site);
  
console.log("Site Data is as follows:");
console.log(`Site name: \t${site.siteName}`);
console.log(`Site url : \t${site.url}`);
console.log(`Founder name: \t${site.founderName}`);
console.log(`About site: \t${site.aboutSite}`);
console.log(`Site Content: \t${site.siteContent}`);


Here, we have imported all the exports from the module “siteData.js” into an object called “site”, and later used them.

Output:

Project Structure

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments