The barrel pattern is a codebase management strategy in JavaScript and TypeScript. This pattern can be leveraged on the frontend or backend.
The core principle leverages the special treatment of the index.js
file to re-export content from sibling files. The power of this pattern is the information hiding it achieves, by only exposing a minimal "public API" of the directory.
For anyone unfamiliar, in javascript the index.js
files defines the behavior of the directory it is in. This means that when you import a directory, e.g., import * from './dir'
, you control what is "seen" in that dir by controlling what gets exported in the index file, e.g., ./dir/index.js
.
Example
(I want to stress again that this pattern will work in more places than just the frontend even though a frontend React app is the example I am going to use here.)
Say you are building a React app that has a Weather
component that shows various weather data like temp, wind, and UV data. You know this will end up being a complicated component to implement but also that you are unlikely to use the subcomponents of the Weather
component elsewhere. Here what your folder structure could look like.
src/components/
src/components/Weather/
src/components/Weather/index.js
src/components/Weather/Weather.jsx
src/components/Weather/WeatherTemp.jsx
src/components/Weather/WeatherWind.jsx
src/components/Weather/WeatherWindSubComponent.jsx
src/components/Weather/WeatherWindSubComponent.test.jsx
src/components/Weather/WeatherUV.jsx
src/components/Weather/useWeather.js
src/components/Weather/useWeather.test.js
// src/component/Weather/index.js
export { default } from './Weather.js'
If you find the above re-export syntax confusing think of it as the index file saying "your default export is also my default export". In fact export { default as default } from '...'
is a syntactically valid equivalent (that I find more confusing).
// src/pages/somePage
import Weather from 'src/components/Weather'
function Page() {
return (
<div>
<Weather />
</div>
)
}
On the frontend there can be a lot of files, Jest files, Storybook files, CSS files, etc., and without a pattern like this it can get out of control quickly. Such a barrel approach is recommended by Josh Comeau in his blog post on React file structure.
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.
The special treatment of index.js
files is similarly leveraged in the Library Pattern in JavaScript and TypeScript.
Also, see the MDN docs on import and export to see other syntactic techniques for achieving the same ends.