import/export β The Core of the Module System
After completing this topic
You will understand the import/export syntax of ES Modules and how to properly organize your code.
Putting all the code in one file
Early JavaScript put all the code in a single file. As the file grew, variable names would collide, it became difficult to find the code, and it could not be reused.
A module is a system that divides code into files and exports and imports only what is needed.
export: Export
There are two ways to export from a file so that it can be used elsewhere.
Named export β export with a name:
// utils.js
export function formatDate(date) {
return date.toLocaleDateString();
}
export const MAX_ITEMS = 100;You can export multiple items from a single file.
Default export β one default export per file:
// Button.js
export default function Button({ label }) {
return <button>{label}</button>;
}import: Import
Named exports are imported using curly braces:
import { formatDate, MAX_ITEMS } from "./utils.js";The names must match exactly. If you want to rename them, use as:
import { formatDate as format } from "./utils.js";Default exports are imported without curly braces:
import Button from "./Button.js";You can freely choose the name:
import MyButton from "./Button.js"; // Same thingNamed vs Default
// Named β multiple exports, fixed name
export function add(a, b) { return a + b; }
export function sub(a, b) { return a - b; }
import { add, sub } from "./math.js";
// Default β one export, free name
export default function Calculator() { ... }
import Calculator from "./Calculator.js";
import Calc from "./Calculator.js"; // Free nameConvention in practice:
- React components: default export (one component per file)
- Utility functions, constants: named export (multiple per file)
You can also use both together:
import React, { useState, useEffect } from "react";React is the default, and useState and useEffect are named.
Import everything
You can import all named exports from a file at once:
import * as utils from "./utils.js";
utils.formatDate(new Date());
utils.MAX_ITEMS;However, it is better to import only what you need. This allows the bundler to remove unused code (tree-shaking).
Key takeaway
Export with
exportand import withimport. Named exports are imported with curly braces, and default exports are imported without curly braces. Components are typically default exports, while utilities/constants are typically named exports.