Barrel Pattern in JavaScript and TypeScript

Image of Author
March 24, 2022 (last updated September 21, 2022)

The barrel pattern is a strategy for containing all related sourcecode files into a single directory while still maintaining a clean interface with the rest of the application. This pattern can be leveraged on the frontend or backend.

The core principle is using an index.[(j|t)sx?] to re-export the exports from sibiling files. Exporting them from the index file will allow you to control what gets exported, and as a result, what gets revealed to the surrounding components. Also, the index.[(j|t)sx?] is the default file used when you import a folder elsewhere. Let's see an example to make it more clear.

component/
|
-- index.js
|
-- component.js
|
-- component.test.js
|
-- subcomponent.js
|
-- subcomponent.test.js
// component/index.js

export * from "./component.js";

import { someFunction } from "./subcomponent.js";
export { someFunction };

Now, elsewhere in the codebase, when you import the component, you can reference merely the folder, which will read from component/index.js, and serve up only the indexed exports:

// in some other file elsewhere

import ComponentClass, { someFunction } from "../component";

Resources

I first came across the barrel pattern in Basarat Ali Syed's digital book, TypeScript Deep Dive, and so use his name for it, the barrel pattern. I also see it used in the frontend community where people with have Jest files, Storybook files, CSS, all right next to their component file. Such a barrel approach is recommended by Josh Comeau in his blog post on React file structure.

Also, see the MDN docs on import and export to see other syntactic techniques for achieving the same ends.