Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 16 Jan, 2022

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 geeks";
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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!