"JavaScript Modules: import and export"
Splitting code across files with ES modules, and the difference between named and default exports.
2 min read
As a program grows past a few dozen lines, keeping everything in one file stops being manageable. ES modules (the standardized import/export syntax) let you split code across files and explicitly control what each file shares with the rest of the program.
Named exports
A file can export multiple named values:
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export const PI = 3.14159;// app.js
import { add, subtract, PI } from "./math.js";
console.log(add(2, 3)); // 5Named imports must match the exported name exactly (they can be renamed with as if needed: import { add as sum } from "./math.js"), and you only import what you actually use.
Default exports
A file can also have one default export — typically the "main thing" that file provides:
// user.js
export default class User {
constructor(name) {
this.name = name;
}
}// app.js
import User from "./user.js"; // no curly braces, and the name is up to you
const u = new User("Ada");Unlike a named import, a default import's local name doesn't have to match anything in the source file — import Whatever from "./user.js" would still work, since there's only one default to grab.
Combining both
// api.js
export default function fetchData() { /* ... */ }
export const BASE_URL = "https://api.example.com";import fetchData, { BASE_URL } from "./api.js";Named vs default: which to use
Named exports make refactors and searches easier — an editor can find every usage of a specific named export, and the import name is enforced to match. Default exports are convenient for a file with one obvious primary export (a single component or class), but two developers importing the same default export can give it two different local names, which makes the codebase harder to search consistently. Many modern style guides lean toward named exports for exactly that reason, reserving default exports for cases where a file truly has one clear "main" thing to offer.
Modules run in strict mode automatically
Code inside an ES module is automatically in strict mode — no "use strict" needed — which is part of why this is undefined (not the global object) in a standalone function call inside a module, as covered earlier in this course.
Modules organize how code is structured across files. The final lessons in this course cover handling things going wrong at runtime — errors — and working with JSON, the data format nearly every API speaks.