How to Export or Import JavaScript Modules?

JavaScript modules play a key role in organizing your code-base.  Let’s learn how to export or import JavaScript modules with examples. When the business expands work flow increases, it requires a huge amount of resources to keep up, especially when your code-base grows as well. It’s where modules come into play. We can organize our JavaScript complex code in small pieces of files “modules.” 

What is a JavaScript module?

A JavaScript module is a set of similar functions/classes or function/class that we use to address a certain issue and callback when needed. It contains the blueprint of code that can be used in different situations and called upon using special directive export/import  with specific keywords when needed stored in modules. 

  • We can use the export keyword to organize a specific function, class or variable to be accessible in other modules.
  • We can use the import keyword in another module to import the function or inject it.  

There are many ways we can use to compile our module files, here in the example code we use .js extensions. Further we might need to use Node.js or Babel for tool building etc. For parsing confirmation as a JavaScript module we can use the .mjs extension.

Let’s see the example below:

// 📁 math.js

export function add(a, b){
	return a + b;
}

export function subtract(a, b){
	return a - b;
}

…Then we call those functions in another file by importing it. As simple as that.

// 📁 main.js 

import { add, subtract } from './math.js';

let x = add(4, 1)
let y = subtract(4, 1)

console.log(x) // 5
console.log(y) // 3

The import keyword will import the function from our math.js module to your main.js. So basically the import keyword that we used loads this module path ./math.js,  by using the relative path of  main.js .

How to export a JavaScript module?

To export a function, variable, class or object we use the export keyword before any declarative variable or function. See below:

// 📁 student.js

// export a variable
export const STUDENT_ID = 'studentId';

  
// export an array
export let subjects = ['Biology', 'Chemistry', 'Physics', 'Geometry', 'Literature'];


// export a class
export class Student {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}


// export a function
export function calculateMarksSubject(arrSubjects){
    console.log(`Count markssubject: ${arrSubjects.length}`)
}

We can also export them as a group in one line instead of this. See the example below:

// 📁 student.js

const STUDENT_ID = 'studentId';

let subjects = ['Biology', 'Chemistry', 'Physics', 'Geometry', 'Literature'];

class Student {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

function calculateMarksSubject(arrSubjects){
    console.log(`Count markssubject: ${arrSubjects.length}`)
}

export { subjects, calculateMarksSubject }

How to import a JavaScript module?

Now we will try to save the student.js file into our  main.js directory. We will use the same method we used above by importing student.js into our main.js directory.

// 📁 main.js 

import { add, subtract } from './math.js';
import { subjects, calculateMarksSubject } from './student.js';

let x = add(4, 1)
let y = subtract(4, 1)

console.log(x) // 5
console.log(y) // 3

// 'subjects' array is retrieved from './student.js' by using import
let marksinBiology = subjects[0];
console.log(marksinBiology)

// call an imported function from './student.js'
calculateMarksSubject(marks);

In the meanwhile we can rename and export any module by using * and group or an object. See the example below:

// 📁 main.js 

import * as math from './math.js';
import { subjects as markssubjects, calculateMarksSubject } from './student.js';

let x = math.add(4, 1) // now we must put math before 'add' function 

// 'subjects' array already renamed as 'markssubjects'
let marksinBiology = marks[0];

This way we can import and export any JavaScript module making the right call. If you are a developer or a database administrator you need to understand the importance this small thing and how to export or import JavaScript modules into others.