Following this answer to the question Is it possible to import modules from all files in a directory, using a wildcard? I was able to import multiple modules in a single declaration, exporting them like this:
Part of /hooks/index.ts
export { default as useSections } from './useSections';
export { default as useArtworkEvents } from './useArtworkEvents';
export { default as useEventBusListener } from './useEventBusListener';
And then importing them in a component like this:
Part of Packaging.tsx
import { useSections, useArtworkEvents, useEventBusListener } from 'src/hooks';
I’m doing the same thing in another project where there are no issues, but here I’m importing large libraries from the modules and all those libraries go into the vendor folder.
The libraries are imported like this:
sample of one of the hooks
import { autorun, IReactionDisposer } from 'mobx';
// body of the module
// and the export in the end
export default useArtworkEvents;
And this is the current situation:
It looks like the first place where one of the files is imported (let's say App.tsx
) is where all the libraries get loaded, even if only one should be imported (in my intentions).
I want to add that this is happening even if the components that use the libraries are loaded dynamically, through React Suspense:
Sample from App.tsx
const PackagingComponent = lazy(
() => import('src/components/PackagingComponent' /* webpackChunkName: "packaging" */)
);
And then
<ErrorBoundary locale={props.locale}>
<Suspense fallback={<Loader />}>
{props.componentType === AcceptedComponentTypes.PACKAGING && (
<DesignStackPackaging
locale={props.locale}
tenant={props.tenant}
/>
)}
{/* ...other conditions */}
</Suspense>
</ErrorBoundary>
Solution?
If I remove the export in the index files (there are two in the project, one for common scripts and the other for hooks) and import the modules directly, the issue will go away.
Part of /hooks/index.ts
export {};
Part of Packaging.tsx
import useSections from 'src/hooks/useSections';
import useArtworkEvents from 'src/hooks/useArtworkEvents';
import useEventBusListener from 'src/hooks/useEventBusListener';
You can see that the issue seems to be solved:
So I’m asking two things:
- Does anyone know why is this happening?
- Is there a more convenient way of exposing modules (without adding a new line for every new import)?
I thought that maybe I could put all the modules that import large libraries in a separate folder where I don’t export them with an index file, while keeping smaller modules in some common folders where I do export them using the index file, but I don’t like the solution as it doesn't feel consistent, and a co-worker which is not aware may take the issue back.
For context I also add the Webpack Split Chunks configuration:
splitChunks: {
chunks: 'all',
name: true,
},
(BTW the same happens if name
is set to false
).