Back to blog
thatonevikash

Barrel file in React Eco-System

Why do we need a barrel file in modern react codebases, how do we use it?, Why modern react codebases loves the barrel file

On this page

Use of a barrel file (index.js or index.ts) with in modern react codebases.

A barrel file is nothing just a index.js or index.ts file within a folder.

It is useful to make import statements shorter and beautiful.

// src/components/avatar/index.js

export * from "./avatar.jsx";

export { classes as avatarClasses } from "./classes.js";
// src/components/avatar/avatar.jsx

export function Avatar() {
  return (
    // Your component
  )
}

// src/components/avatar/classes.js

export const classes = {
  root: 'avatar__root',
}
import { Avatar } from "@components/avatar"; // with barrel file
import { Avatar } from "@components/avatar/avatar"; // without barrel file

export default function Page() {
  return (
    <>
      <Avatar src="/assets/user.png" />
    </>
  );
}

Warning

named export and default export behaves differently in modules.

If your component looks like this

export default function Avatar() {
  return (
    // Your component
  )
}

If file is getting default exported 👇

// src/components/avatar/index.js

export * from "./avatar.jsx"; 
export { default } from "./avatar.jsx"; 

export { classes as avatarClasses } from "./classes.js";

Modern react codebases prefers named export for component.