I have a lot of minor components:
export const A = () => {...}
export const B = () => {...}
...
export default [A, B, ...];
After adding another component to the file, I might forget to add it to the export default [...]
. By now you should see what the problem is.
How should I resolve this issue? Is it maybe possible to define a list that includes all exported functions?
I want to be able to iterate over all components in other files. Hence why it has to be a list they are grouped into.
CodePudding user response:
origin file src/foo.js
:
export const A = () => { ... };
export const B = () => { ... };
export const C = () => { ... };
Create an src/index.js
as following:
import foos from './foo';
const allComponents = Object.values(foos);
export default allComponents;
From another file we'd:
import foos from 'src/foo';
foos[0]() // A()
foos[1]() // B()
...
EDIT: fixed the example code, needs to use values()
not keys()
, my bad
CodePudding user response:
With some minor modifications, you can use import *
. This gives you all of the named exports of a file, wrapped up into an object. If, for example, your old code was doing this:
import allComponents from 'someFile'
allComponents.forEach(component => {
// do something with the component
})
... instead do this:
import * as allComponents from 'someFile'
Object.values(allComponents).forEach(component => {
// do something with the component
})
As new exports are added to the file, this import statement will pull them in automatically, and so the default export array shouldn't be needed anymore.