Member-only story

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

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.

Responses (6)

What are your thoughts?

Thoughtful piece. Good work!
However, I wonder how much is really an issue with barrel files, and how much is an issue with sloppy dependency management and bad component design.
For instance, in my mind, having a circular dependency is a symptom of…

Very insightful article Steven. I am even curious to kno, how you found out that jest was importing all the unused code

This is the best article, i've ever seen recently. Thank you very much.

Recommended from Medium

Lists

See more recommendations