Are TypeScript Barrel Files an Anti-pattern?

Steven Lemon
12 min readFeb 1, 2023
Photo by Daniel Vogel on Unsplash

Barrel files are a popular pattern in Typescript projects for managing imports and exports. Rather than importing dependencies straight from the source file location, we add an intermediary index.ts file that re-exports a module’s dependencies. Barrel files let us shorten and simplify import statements, prevent the consumer from needing to concern themselves with the internal implementation of the module, and provide a public interface behind which we can freely refactor.

For example, we might have a React component with the following folder structure:

/src/components/componentA
ComponentA.tsx
ComponentA.test.ts
ComponentA.types.ts
ComponentA.styles.ts
index.ts

Within that folder, there are going to be a bunch of export statements passing objects between the files that aren’t relevant to the rest of the application. In most cases, someone consuming this component will only be interested in ComponentA and perhaps an interface for its properties. With barrel files, we can export just these objects from the folder.

// src/components/componentA/index.ts
export { ComponentA } from './ComponentA.ts';
export { ComponentAProps } from './ComponentA.types.ts';

Then, from another file, we can import from the folder path, rather than specific files.

--

--

Steven Lemon
Steven Lemon

Written by Steven Lemon

Lead Software Engineer and occasional Scrum Master. Writing about the less technical parts of being a developer.