Photo by Moritz Kindler on Unsplash

In JavaScript, we can use the single module and reuse it in different scripts for several times by Importing and Exporting it.

Import JavaScript modules 01

In Node JS we mostly use require keyword to import module from another place,

and ES 6 importing is done by import keyword

Let’s see some Examples,

const importedModule = require('./Folder1/File2.js') ;import importedModule from './Folder1/File2.js' ;console.log(importModule.performSomething()) ;//Invoking performSomething() from ./Folder1/File2.js

In Node JS we mostly use require keyword from importing Modules

Export JavaScript Modules

To make an Object in our file to be exportable, we assign that module to exports

which is the property module .

const person = {} ;module.exports = person ;

export default in JavaScript

As a feature of ES 6, we can have default export one function or variable in a file that can be imported in a straight forward manner. instead of requiring we may use import to import the default exported object

//file add.js
let sayName = function(){
return "Hellen" ;
}
export default sayName ;//file index.js
import sayName from './add.js' ;
console.log(sayName()) ;
//Hellen

NOTE : use type = module in JSON file to use ES functionality in Node JS

Import JavaScript modules 02

ES 6 feature import keyword can be used in different ways like import * from './module.js'

where all the functions and variables that are exported can be used

A single function can be imported with curly brackets as follows:

import {funcA} as name from 'module_name';

Or many functions by name:

import {funcA, funcB} as name from 'module_name';

// add.js
export const add = (x, y) => {
return x + y
}
// index.js
import { add } from './add';
console.log(add(2, 3)); // 5

NOTE: Many get confused with import funA , {funB, funC} from 'module_name' ;

here funA is a default Export and the rest are not default Export, One file can have only one default Export.