JavaScript Modules & Import/Export-ES6 Modules

6/29/2025
All Articles

module-vs-commonjs.png: "Comparison chart of ES6 Modules and CommonJS syntax

JavaScript Modules & Import/Export-ES6 Modules

JavaScript Modules & Import/Export (ES6 Modules)

Modern JavaScript development is all about writing modular and maintainable code. With the introduction of ES6 Modules, developers can now split their code into reusable pieces across multiple files using import and export statements. This makes code easier to organize, scale, and debug.


What are JavaScript Modules?

A module in JavaScript is just a file that contains code. ES6 Modules allow you to export variables, functions, classes, or entire objects from one file and import them into another.

This helps in:

  • Avoiding global scope pollution

  • Promoting code reusability

  • Managing dependencies cleanly


🔹 Exporting in JavaScript

There are two types of exports in ES6:

1. Named Export

You can export multiple things from a file:

// utils.js
export const PI = 3.14;
export function add(a, b) {
  return a + b;
}

2. Default Export

Use when you want to export a single value/function:

// logger.js
export default function log(message) {
  console.log("Log:", message);
}

Importing in JavaScript

Importing Named Exports:

import { PI, add } from './utils.js';
console.log(add(5, PI));

Importing a Default Export:

import log from './logger.js';
log("App started");

Renaming Imports:

import { add as sum } from './utils.js';
sum(2, 3);

Combining Named and Default Imports

// index.js
import log from './logger.js';
import { PI, add } from './utils.js';

log(add(PI, 2));

🔹 Dynamic Imports (Import on Demand)

Dynamic import() is useful when you want to load modules only when needed:

button.addEventListener('click', async () => {
  const module = await import('./math.js');
  console.log(module.multiply(2, 3));
});

🔹 How to Use ES6 Modules in Browser

Use type="module" in your HTML:

<script type="module" src="main.js"></script>

Note: You must run your code via a local server (not file://) due to CORS policies.


🔹 How to Use Modules in Node.js

  • Use .mjs extension or add "type": "module" to package.json.

{
  "type": "module"
}
  • Import files using relative or absolute paths with file extensions:

import { add } from './utils.js';

 

Conclusion

JavaScript Modules are a game changer in modern web development. They enable a clean, scalable code structure with well-defined boundaries between functionalities. With import and export, you can write maintainable code and manage dependencies more efficiently.

Whether you’re building web apps or server-side JavaScript in Node.js, mastering ES6 Modules is essential to writing professional JavaScript code.

Article