Sub topic 2
Named Exports
This chapter assumes you know core JavaScript syntax, including destructuring. You should know how let, const, and var differ, and how to run a file with Node.js or in a browser. The previous chapter explained that every module has its own scope. A named export is how a module chooses which of its top-level bindings other modules may see, and under what names.
What a Named Export Is
A named export makes a top-level binding (a variable, function, or class) available to other modules under a specific name. The importing module must ask for that exact name. A module can have any number of named exports. Anything the module does not export stays private.
JavaScript gives you two ways to write named exports:
- Put
exportin front of a declaration (an inline export). - Declare things normally, then list them in an
export { ... }statement (an export list). An export list can rename bindings withas.
The following module uses both:
// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}
function circumference(radius) {
return 2 * PI * radius;
}
export { circumference as perimeter };This module has three named exports: PI, area, and perimeter. The local function is called circumference, but consumers never see that name. They only see perimeter.
To use these exports from another file:
// main.js
import { PI, area, perimeter } from './math.js';
console.log(PI); // 3.14159
console.log(area(2)); // 12.56636
console.log(perimeter(2)); // 12.56636To run this in Node.js, put both files in a folder whose package.json contains "type": "module", then run node main.js. A later chapter covers Node's module configuration in detail. Importing gets its own chapter too. For now, the curly braces just list the export names being requested.
Inline Exports
You can put export in front of any declaration at the top level of a module:
// inline.js
export let counter = 0;
export var legacyFlag = true;
export const MAX = 10;
export function double(n) {
return n * 2;
}
export async function fetchJson(url) {
const response = await fetch(url);
return response.json();
}
export function* range(start, end) {
for (let i = start; i < end; i += 1) yield i;
}
export class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const options = { width: 800, height: 600 };
export const { width, height } = options;The last line shows that destructuring declarations work. Each name the pattern creates (width and height) becomes its own named export.
With inline exports, the export name always equals the local name. You cannot rename a binding in an inline export.
Export Lists and Renaming
An export list collects your exports in one place, often at the bottom of the file. Many teams like this style because a reader can see the whole public API at a glance:
// strings.js
function capitalize(text) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
function slugify(text) {
return text.toLowerCase().trim().replace(/\s+/g, '-');
}
const SEPARATOR = '-';
export { capitalize, slugify as toSlug, SEPARATOR };The local as exported syntax splits the name you use inside the module from the name you publish. This helps in several situations:
- Keeping internal names descriptive. The local name can describe the implementation, and the exported name can describe the purpose.
- Exporting one binding under two names.
export { slugify, slugify as toSlug };is valid, so you can keep an old name working while you introduce a new one. - Avoiding reserved words. A local binding cannot be called
delete, butexport { remove as delete };is allowed, because export names may be any identifier name, including reserved words.
Since ES2022, an export name can also be a string literal. This matters mostly for tools that work with other languages:
// strings-extra.js
const greeting = 'hello';
export { greeting as 'greeting-text' };The importer has to rename it back to an identifier: import { 'greeting-text' as greetingText } from './strings-extra.js';.
Rules the Engine Enforces
Modules are parsed before any code runs, so export mistakes cause a SyntaxError at load time. The program fails before its first line executes. The rules are:
| Rule | Invalid example | Result |
|---|---|---|
| Export names must be unique | `export const a = 1; export { b as a };` | SyntaxError: duplicate export |
| Exports only at the top level | `if (ok) { export const x = 1; }` | SyntaxError |
| A listed binding must exist in the module | `export { missing };` | SyntaxError: export not defined |
| An inline export needs a declaration | `export 42;` or `export x + 1;` | SyntaxError |
| An export list holds names, not expressions | `export { obj.prop };` | SyntaxError |
An export list may appear before the declarations it names, because exports are resolved after the whole module has been parsed:
// order.js
export { greet };
function greet(name) {
return `Hello, ${name}`;
}Order does matter in one case. If another module reads a let or const export before the exporting module has run that declaration, the read throws a ReferenceError. A later chapter on circular dependencies explains when this happens.
Common Errors
Expecting an object. export { a, b } looks like an object literal, but it is not one. You cannot write export { a: 1 }, and you cannot write export { obj.a }. To export a computed value, give it a name first: export const total = a + b;.
Mismatched names. The importer must use the exported name exactly. Names are case-sensitive. If math.js exports perimeter, then import { circumference } from './math.js' fails at link time with a SyntaxError that says the module does not provide an export named circumference.
Confusing renaming with destructuring. Renaming uses as (slugify as toSlug). The destructuring colon (slugify: toSlug) is not allowed in an export list.
Exporting too much. Every export becomes part of the module's public contract, and other code may come to depend on it. Keep helpers private unless a consumer needs them.
Exercises
Exercise
A module contains function toCelsius(f) { return (f - 32) * 5 / 9; }. Write one export statement that publishes this function under both the name toCelsius and the name fToC.
Show answer
export { toCelsius, toCelsius as fToC }; One local binding can appear more than once in an export list, as long as each export name is unique.
Exercise
Which lines cause a SyntaxError, and why? (1) export const { x, y } = point; (2) export { total as default2, total as default2 }; (3) export { config.port }; (4) export { run }; function run() {}
Show answer
Line 2 fails because it uses the export name default2 twice. Line 3 fails because an export list can contain only binding names, not property access expressions. Line 1 is valid because destructuring creates the exports x and y. Line 4 is valid because an export list may come before the declaration it refers to.
Exercise
A file declares const delete_ = (id) => {} and wants consumers to see it as delete. Is export { delete_ as delete }; allowed? Is export const delete = () => {}; allowed?
Show answer
The first is allowed, because export names may be reserved words. The second is a SyntaxError, because delete cannot be used as a variable name in a declaration.