Skip to main content

Modules and Code Organization

Barrel Files and Public APIs

0:00
LearnStep 1/3

Simplifying Imports with Barrels

In modular JavaScript development, projects often grow to have deeply nested directory structures. Without organization, import statements can become long and repetitive, exposing the internal file structure to consumers.

A barrel file (typically named index.js or index.ts) serves as a central point of entry for a directory. It re-exports selected exports from other modules in that directory, effectively creating a public API for that folder.

Basic Re-exporting

The most common pattern is using export * to expose everything from a sibling file:

javascript

This allows consumers to import from the folder path rather than specific files:

javascript

Controlled Visibility and Aliasing

Sometimes you want to hide internal helpers or rename exports to provide a better consumer experience. You can use named exports for this:

javascript

The Risk of Circular Dependencies

Barrel files can sometimes lead to circular dependencies if modules within the barrel import from the barrel itself (e.g., trying to reach a sibling) instead of importing the sibling directly. Always import siblings directly using relative paths inside the directory, and reserve the barrel for external consumers.