Sub topic 9
Re-exports and Barrel Modules
This chapter assumes you already know named and default exports, the import forms (named, default, namespace, renamed), and how relative specifiers like ./math.js resolve.
A re-export passes another module's exports through the current module. The export ... from syntax does this in one statement. A barrel module is a single file, usually index.js, that re-exports names from several modules so consumers can import everything from one place.
The export ... from Forms
Suppose math.js exports area and perimeter, and logger.js has a default export. Add two small modules:
// shapes/polygons.js
export function square(side) {
return side * side;
}
export function triangle(base, height) {
return (base * height) / 2;
}// shapes/units.js
export const CM = 'cm';
export const INCH = 'in';The barrel combines them:
// 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';Consumers now need one specifier:
// main.js
import { area, square, log, units } from './shapes/index.js';
log(`area=${area(2)}, square=${square(3)}, unit=${units.CM}`);| Form | What the barrel exposes |
|---|---|
| `export { a, b } from './m.js'` | Only the listed names |
| `export { default as x } from './m.js'` | The default export, under the name `x` |
| `export * from './m.js'` | Every named export, but not the default |
| `export * as ns from './m.js'` | A single namespace object named `ns` |
Common Errors
Expecting a Local Variable
export { area } from './math.js' does not create an area variable inside index.js. If the barrel itself needs to call area, it must also import it with import { area } from './math.js'.
Losing the Default Export
export * skips default. To forward a default export, name it explicitly with export { default } from './m.js' or export { default as name } from './m.js'.
Name Collisions
If two export * sources export the same name, the barrel exports neither copy. The conflict stays silent until a consumer imports that name, and then linking fails with a SyntaxError. To fix it, re-export one of the names explicitly. An explicit export takes priority over the export * versions.
Exercise
A barrel contains export * from './a.js' and export * from './b.js', and both modules export format. What happens when main.js runs import { format } from './index.js', and how do you make format refer to the one in a.js?
Show answer
The name is ambiguous, so the import fails at link time with a SyntaxError. Add export { format } from './a.js'; to the barrel. An explicit export takes priority over star exports.
Exercise
Why does import log from './shapes/index.js' fail with the barrel above?
Show answer
The barrel has no default export. It re-exports logger.js's default under the name log, so you import it with import { log } from './shapes/index.js'.