JavaScript modules are a fundamental building block for modern web applications. They allow us to organize code into reusable units. When working with modules, you’ll encounter two primary ways to import code: default exports and named exports. Let’s break down the differences.
Default Exports:
A module can have only one default export. It’s the primary export of a module, often representing the main functionality.
import userRouter from "./routes/user.router.js";
Here, userRouter is the name given to the imported default export.
Named Exports:
A module can have multiple named exports. These are explicitly defined using the export keyword.
import { userRouter } from "./routes/user.router.js";
Here, userRouter is the name of the specific named export being imported.
Key Differences
- Number of exports: A module can have only one default export, but multiple named exports.
- Syntax: Default exports use
import ... from, while named exports useimport {...} from. - Curly braces: Curly braces are not required for default exports but are mandatory for named exports.
When to Use Which?
- Default export: Ideal for the primary functionality of a module.
- Named exports: Useful for exporting multiple related functions, components, or variables.
Example:
// user.router.js
export default function userRouter() {
// Router logic
}
export const anotherExport = "some value"; // Named export
// main.js
import userRouter from "./user.router.js"; // Importing default export
import { anotherExport } from "./user.router.js"; // Importing named export