Sub topic 9
Re-exports and Barrel Modules
This chapter assumes you know named exports, default exports, and the import forms covered earlier, and that imports are live bindings. You should be able to run a small set of ES module files in Node.js or a browser.
A re-export passes another module's exports through the current module without importing them for local use. A barrel module is a file, usually named index.js, that consists mostly of re-exports. It gives a folder of modules one public entry point. Consumers import from the barrel and do not need to know which internal file defines each name.
The re-export forms
The export ... from declaration combines an import and an export in one statement. Here is a complete set of files you can run.
// shapes/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 };// shapes/logger.js
export default function log(message) {
console.log(`[app] ${message}`);
}
export const level = 'info';// shapes/polygons.js
export function squareArea(side) {
return side * side;
}
export function triangleArea(base, height) {
return (base * height) / 2;
}// shapes/units.js
export const CM_PER_INCH = 2.54;
export function toCm(inches) {
return inches * CM_PER_INCH;
}
export default 'metric';// shapes/index.js
export { area, perimeter } from './math.js';
export { default as log } from './logger.js';
export * from './polygons.js';
export * as units from './units.js';// main.js
import { area, perimeter, log, squareArea, units } from './shapes/index.js';
log(`area=${area(2)}`);
log(`perimeter=${perimeter(2)}`);
log(`square=${squareArea(3)}`);
log(`10in=${units.toCm(10)}cm, system=${units.default}`);Running node main.js (with "type": "module" in package.json, or with .mjs extensions) prints four [app] lines.
Each line in index.js does something different:
| Form | What it exports | Includes the default export? |
|---|---|---|
| `export { a, b } from './m.js'` | Only the listed names | Only if you list `default` |
| `export { a as b } from './m.js'` | `a` under the new name `b` | Not applicable |
| `export { default as log } from './m.js'` | The source's default export as a named export `log` | Yes, renamed |
| `export { area as default } from './m.js'` | A named export as the barrel's default export | Not applicable |
| `export * from './m.js'` | Every named export of the source | No |
| `export * as ns from './m.js'` | One named export `ns`, a namespace object | Yes, as `ns.default` |
Re-exports do not create local bindings
A common mistake is to use a re-exported name inside the barrel itself:
// shapes/index.js
export { area } from './math.js';
console.log(area(1)); // ReferenceError: area is not definedexport ... from links the barrel's export straight to the source module's binding. It never declares area in the barrel's scope. If the barrel needs the value too, import it separately:
// shapes/index.js
import { area } from './math.js';
export { area };
console.log(area(1)); // 3.14159The two versions look alike to consumers, and both keep the binding live. Changes to an exported let in the source module show up through the barrel, because the re-export points at the original binding and does not copy its value.
How names resolve through a barrel
When the engine links main.js, it resolves each imported name by following re-exports until it reaches the module that declares the binding.
All of this happens during linking, before any code runs. A missing name, such as import { volume } from './shapes/index.js', is a SyntaxError at link time, and no module in the graph evaluates.
Name conflicts in star exports
Two export * declarations can supply the same name. Suppose polygons.js and a new solids.js both export volume:
// shapes/solids.js
export function volume(side) {
return side ** 3;
}
export function cubeSurface(side) {
return 6 * side * side;
}// shapes/index.js
export * from './polygons.js'; // assume this now also exports volume
export * from './solids.js';The language does not choose a winner. These rules apply:
- The ambiguous name
volumeis quietly left out of the barrel's exports. Loading the barrel does not throw. - Importing
volumeby name from the barrel is a link-timeSyntaxError. Node.js reports conflicting star exports for that name. import * as shapesdoes not throw. It produces a namespace object that has novolumeproperty.- An explicit export in the barrel takes priority over star exports. Adding
export { volume } from './solids.js'makesvolumerefer to the version insolids.js.
Rule 3 is the dangerous one. Code that reads shapes.volume gets undefined and fails later, far from the cause. When you use several star exports, list colliding names explicitly or use export * as to keep each module in its own namespace.
The costs of barrel modules
Barrels make imports tidy, but they have costs worth weighing.
Loading more than you use
Importing one name from a barrel loads and evaluates every module the barrel references. Bundlers can drop unused code when the modules have no side effects. Unbundled environments cannot: native browser modules, Node.js, and test runners such as Jest or Vitest all fetch and run each file. A barrel over 200 icon components can slow test startup and page loads a lot.
Circular dependencies inside the package
If polygons.js imports a helper from ./index.js and not from ./math.js, it creates a cycle: index.js loads polygons.js, which depends on index.js. Cycles can surface bindings that are not yet initialized. A later chapter covers this in detail. The rule that prevents it is simple: internal modules import from each other directly, and only outside consumers use the barrel.
Hidden API surface
export * makes every future export of a source file public automatically. An internal helper that someone adds to polygons.js becomes part of your package's API without anyone deciding it should. Explicit lists cost more typing but keep the public surface deliberate.
Choosing a style
| Situation | Recommended approach |
|---|---|
| Package entry point with a stable API | Barrel with explicit `export { ... } from` lists |
| Large set of similar modules (icons, locales) | Deep imports or a bundler that handles side-effect-free packages, not one big barrel |
| Grouping related helpers for consumers | `export * as name from` to avoid collisions |
| Code inside the same package | Direct imports from the defining file, never the barrel |
Exercise
A barrel contains export * from './a.js'; and export * from './b.js';. Both a.js and b.js declare and export their own format function. What happens with import { format } from './index.js', and what happens with import * as lib from './index.js' followed by lib.format?
Show answer
The named import fails at link time with a SyntaxError, because format is ambiguous and is excluded from the barrel's exports. The namespace import succeeds, but lib.format is undefined, because ambiguous star exports are left out of the namespace object. Adding an explicit export { format } from './a.js'; to the barrel resolves the conflict.
Exercise
Why does export { area } from './math.js'; console.log(area(1)); throw a ReferenceError inside the barrel, and how do you fix it while still re-exporting area?
Show answer
export ... from links the export directly to math.js's binding and does not create a local area binding in the barrel's scope. Fix it by writing import { area } from './math.js'; followed by export { area };, which declares a local binding and exports it.
Exercise
units.js has a default export and the named export toCm. Write a single barrel line that exposes toCm to consumers and also exposes the default export under the name unitSystem.
Show answer
export { toCm, default as unitSystem } from './units.js';