Richard Oey

JavaScript modules - How to use export & import

Created August 17, 2022

Introduction

The amount of code increases as the complexity and business logics grows. Developer needs to think how to maintain and organize the files so it will be clear and easy to read. One approach is by "splitting" into multiple files, so called "modules".

What is module?

A module is a file that may consist of a group of similar functions or class for a specific purpose.

Modules can be called or loaded using special directives export and import.

The example code will use .js extensions for our module files. You may need to use Node.js or build tools such as Babel. However, you also can use .mjs extension that ensures your module files are parsed as a module by runtimes.

For instance, take a look at below code.

// 📁 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(3, 2)
let y = subtract(3, 2)

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

The import directive will bring the function from math.js to your main.js. Moreover, in this case, the import directive loads the module by path ./math.js, means it will use the relative current path of main.js .

Deep dive into export

How to export ?

We can put export before any declaration of variable, class, or function.

// 📁 employee.js

// export a variable
export const EMPLOYEE_ID = 'employeeId';

  
// export an array
export let days = ['Monday', 'Tuesday', 'Thursday', 'Friday', 'Saturday'];


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


// export a function
export function calculateWorkDay(arrDays){
    console.log(`Count workday: ${arrDays.length}`)
}

or you can export them in one line as a group

// 📁 employee.js

const EMPLOYEE_ID = 'employeeId';

let days = ['Monday', 'Tuesday', 'Thursday', 'Friday', 'Saturday'];

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

function calculateWorkDay(arrDays){
    console.log(`Count workday: ${arrDays.length}`)
}

export { days, calculateWorkDay }

How to import ?

Store above employee.js file in the same level of main.js directory. Using the same approach with the previous example, we will import employee.js in main.js .

// 📁 main.js 

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

let x = add(3, 2)
let y = subtract(3, 2)

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

// 'days' array is retrieved from './employee.js' by using import
let firstDayofWork = days[0];
console.log(firstDayofWork)

// call an imported function from './employee.js'
calculateWorkDay(days);

you also can rename what you export with as keyword and export everything from a module using * and group it as one object.

// 📁 main.js 

import * as math from './math.js';
import { days as workdays, calculateWorkDay } from './employee.js';

let x = math.add(3, 2) // now we need to put math before 'add' function 

// 'days' array already renamed as 'workdays'
let firstDayofWork = workdays[0];

Conclusion

In this modern era, where JavaScript already evolved to be a very powerful programming language for many cases such as Web UI, API, and desktop application), it's necessary to understand how JavaScript modules work, especially how to export and import file correctly. In the end, it's our job (read: developer) to organize their project files so it will be easy to maintain.