Lesson 72 - Named Exports in JavaScript Modules
JavaScript Modules allow us to break our code into separate files, making it more maintainable and organized. One way to share functions, variables, or classes between files is by using named exports.
What Are Named Exports?
Named exports allow you to export multiple values from a file. Each value must be referenced by its exact name when imported.
Syntax: Exporting
You can export as you declare, or export later in a list.
Example 1: Export As You Declare
// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Example 2: Export later
// mathUtils.js
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
export { multiply, divide };
Syntax: Importing Named Exports
To import named exports, you use curly braces {} and the exact exported names.
// main.js
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
If you only need one or two of the exported members, you can import just those:
import { multiply } from './mathUtils.js';
Renaming While Importing
You can rename a named export during import using **as**
:
import { add as addition } from './mathUtils.js';
console.log(addition(2, 3)); // 5
Key Points
- Named exports let you export multiple bindings (functions, variables, objects) by name.
- You can mix export styles in the same file.
- When importing, the names must match unless you rename them using as.
Try Your Hand
- Create a file
helpers.js
with two functions:capitalize
andlowercase
. Export both. - In
app.js
, import and use both functions. - Try renaming
capitalize
tomakeUpper
when importing.