Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an index (barrel) file without breaking react-refresh?

Say I have a module foo and it's got some stuff in it:

// foo/index.js
export { default as SomeComponent } from './SomeComponent'
export { someUtil } from './utilities'
export const SOME_CONSTANT = 42

Now I can import everything I need directly from foo without seeing implementation details about which file something is in:

// bar.js
import { SomeComponent, someUtil, SOME_CONSTANT } from 'foo'

So I got that going for me, which is nice.

But now I get eslint errors from my react-refresh/only-export-components rule warning me that "Fast refresh only works when a file only exports components". Ok, it's true that index.js exports both components and other stuff (functions, constants). Does this rule mean that my foo module/package basically can't effectively use an index file -- i.e., that either the components or the other stuff will have to be imported directly from wherever they are used?

// bar.js
import { SOME_CONSTANT, someUtil } from 'foo'
import SomeComponent from 'foo/SomeComponent'

Am I understanding the react-refresh rule here? If so, what's the recommended pattern for module-level exports that doesn't break it?

like image 623
Sasgorilla Avatar asked Jan 19 '26 08:01

Sasgorilla


1 Answers

React Fast refresh needs a clear way to detect which files are for components. To fix this, separate your exports into two files -

  1. foo/components.js file - for components export
  2. foo/index.js - for utilities and constants export.

This approach follows the react-refresh/only-export-components rule and allows for project scaling. It keeps things clean and avoid headaches down the road.

// foo/components.js
export { default as SomeComponent } from './SomeComponent';

.

// foo/index.js
export { someUtil } from './utilities';
export const SOME_CONSTANT = 42;

To import:

import { SomeComponent } from 'foo/components';
import { someUtil, SOME_CONSTANT } from 'foo';
like image 84
Ayantunji Timilehin Avatar answered Jan 20 '26 21:01

Ayantunji Timilehin