Understanding ES Module Syntax
🎯 Introduction
This article introduces ES modules (ESM), the module standard added in ES6. You will learn to split and organize code with import and export to improve maintainability and reuse. Modules also integrate with modern build tools and browsers, avoid naming conflicts, and help you organize JavaScript applications.
📦 What Are ES Modules?
Modular programming splits complex code into smaller pieces, each focused on one task. Earlier JavaScript module systems included CommonJS, commonly used in Node.js, and AMD, but neither was part of the language standard. ES6 introduced JavaScript's own module system, ES modules (ESM).
ESM is JavaScript's native module system, supported by browsers and Node.js. Use export to expose variables, functions, or classes, and import to use them in other files, enabling code separation and reuse.
🚀 Basic ESM Usage
Exporting (export)
You can export variables, functions, objects, and classes:
// math.js
export const PI = 3.14159;
export function add(x, y) {
return x + y;
}
export class Calculator {
subtract(a, b) {
return a - b;
}
}
You can also export several bindings at once:
const name = 'ES6 ESM';
function greet() {
console.log('Hello ESM!');
}
export { name, greet };
Importing (import)
Import all exported members or select the ones you need:
import { PI, add } from './math.js';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
You can give imports aliases:
import { add as sum } from './math.js';
console.log(sum(5, 6)); // 11
Import a module namespace as an object:
import * as math from './math.js';
console.log(math.PI);
console.log(math.add(1, 2));
🧩 Default and Named Exports
ESM supports two kinds of exports:
- Named exports: As shown above, bindings are exported by name and imported using those names.
- Default exports: A module can have one default export, suitable for its primary functionality.
For example, a default export:
// logger.js
export default function log(message) {
console.log('Log:', message);
}
Import a default export without braces:
import log from './logger.js';
log('Hello ESM!');
A default export can also be a variable, object, array, or class:
export default {
version: '1.0',
info() {
console.log('ES module information');
},
};
🔄 ESM Characteristics and Considerations
- ES modules run in strict mode automatically; you do not need to write
'use strict'. - Variables declared in a module have module scope and are not directly accessible outside it.
- Imports support static analysis: dependencies can be determined before execution. Static import declarations do not load modules dynamically; ES2020 provides dynamic
import(), covered below. - Prefer
letandconstfor top-level module variables. - Module loading is asynchronous, while the browser respects dependencies between modules.
- In browsers, use relative or absolute module URLs and include file extensions in import paths.
🧪 A Practical Example
Suppose a web project has utility functions for dates, strings, and arrays. Keeping them in one file becomes hard to manage. With ESM, split them into separate modules:
// dateUtils.js
export function formatDate(date) {
return date.toISOString().slice(0, 10);
}
// stringUtils.js
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// arrayUtils.js
export function unique(arr) {
return [...new Set(arr)];
}
Import them in the main file:
import { formatDate } from './dateUtils.js';
import { capitalize } from './stringUtils.js';
import { unique } from './arrayUtils.js';
console.log(formatDate(new Date()));
console.log(capitalize('hello'));
console.log(unique([1, 2, 2, 3]));
This keeps the structure clear, simplifies maintenance, and makes collaboration easier.
Tip
In a browser, load an ES module with a <script type="module"> tag:
<script type="module" src="./main.js"></script>
This tells the browser to treat the script as a module and enables import and export.
Note
To use ESM in Node.js, explicitly set "type": "module" in package.json or use the .mjs extension so the files are interpreted as ES modules. A mismatched module configuration can cause import errors.
🔎 Dynamic Import with import()
ES2020 introduced dynamic import, which loads a module on demand and returns a Promise:
async function loadModule() {
const math = await import('./math.js');
console.log(math.add(1, 2)); // 3
}
loadModule();
This is useful for on-demand loading and code splitting.
❓ Knowledge Check
Q1: How do ES modules differ from CommonJS?
ESM is JavaScript's standard module system, with static import/export syntax that supports static analysis. CommonJS is the earlier Node.js module system, uses dynamic require calls, and is not natively supported by browsers.
Q2: Can module file extensions be omitted?
Browser imports generally need the .js extension. In Node.js, extension handling depends on the module system and configuration.
Q3: What is a default export?
A module can have one default export. Import it without braces and choose any local name for it.
🧪 Exercises
- Create a
utils.jsmodule with a named export,double, that doubles a number, and a default export,square, that squares a number. Import and use both in another file.
// utils.js
// Write your code here
// main.js
// Import and use double and square here
- Load the module on demand with dynamic import and call its functions.
// main.js
// Dynamically import utils.js and call its functions here
🎉 You now understand ES6 modules, static imports, and dynamic imports! Use them to organize frontend code more effectively.
