ES Modules: import & export
Before ES6, JavaScript lacked native module support. Developers relied on external bundlers or global variables, which caused namespace pollution.
ES Modules (ESM) are now the official web standard, enabling file separation, encapsulation, and code reuse.
1. Enabling ES Modules in the Browser
To use import and export statements directly in the browser, you must declare type="module" in the <script> tag:
<script src="main.js" type="module"></script>Note: Scripts marked as type="module" behave like they have the defer attribute by default (executing only after HTML is parsed) and run in Strict Mode.
2. Named Exports
Named exports let you export multiple variables or functions from a single file. You must import them using the exact same names wrapped in curly braces.
// math.js (Module file)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}Importing Named Exports:
// main.js
import { PI, add } from './math.js';
console.log(PI); // 3.14159
console.log(add(5, 5)); // 10Renaming Imports (Alias):
import { add as sum } from './math.js';
console.log(sum(2, 3)); // 53. Default Exports
A module can only have one default export. It is imported without using curly braces, and you can name the import whatever you like.
// Logger.js (Module file)
export default class Logger {
log(msg) {
console.log(`[LOG]: ${msg}`);
}
}Importing Default Exports:
// main.js
import CustomLogger from './Logger.js'; // Notice: no curly braces!
const logger = new CustomLogger();
logger.log("Hello from ES Modules!");4. Combining Named and Default Exports
A module can export both a default item and named items:
// auth.js
export const roles = ["admin", "user"];
export default function login() {
console.log("Logged in!");
}// main.js
import login, { roles } from './auth.js';In the next guide, we will learn how to store data directly in the browser using Web Storage APIs.