JavaScript Modules & Import/Export-ES6 Modules
module-vs-commonjs.png: "Comparison chart of ES6 Modules and CommonJS syntax
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.
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
There are two types of exports in ES6:
You can export multiple things from a file:
// utils.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
Use when you want to export a single value/function:
// logger.js
export default function log(message) {
console.log("Log:", message);
}
import { PI, add } from './utils.js';
console.log(add(5, PI));
import log from './logger.js';
log("App started");
import { add as sum } from './utils.js';
sum(2, 3);
// index.js
import log from './logger.js';
import { PI, add } from './utils.js';
log(add(PI, 2));
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));
});
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.
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';
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.