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?
React Fast refresh needs a clear way to detect which files are for components. To fix this, separate your exports into two files -
foo/components.js file - for components exportfoo/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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With