I'm using create-react-app (react-scripts
4.0.3)/Ionic React to build a mobile app.
I'm having trouble with tree shaking, which according to this answer has been supported since v2.x of create-react-app.
I'm using Webpack Bundle Analyzer to analyzer my bundle size. I'm splitting up the bundle with React.lazy()
and Suspense
.
However, I noticed an issue in which a whole file is being imported instead of just a function.
I'm using react-query and I have a list of functions, queries.tsx:
import { addDataReferences } from '../utils/dataRefs';
export function useLoginStatusCookie(): UseQueryResult<boolean, Error> {
const t0 = performance.now();
return useQuery<boolean, Error>(
queryKeyCookieLoginStatus,
async () => doWeHaveLoginToken()
);
}
export function useSomeData(
queryKey: string,
query: string,
): UseQueryResult<MyDataReferences[], Error> {
return useQuery<MyDataReferences[], Error>(
queryKey,
async () => fetchGetWithUserAuth(query),
{
onSuccess: (data) => {
if (data?.[0]) {
data.map(addDataReferences);
}
},
},
);
}
Now, in my React component, I import useLoginStatusCookie()
like this:
import { useLoginStatusCookie } from '../../queries';
What I expected this to do was to simply import the useLoginStatusCookie
function and not the useSomeData
function, and definitely not the dataRefs.tsx
file imported by the useSomeData
function.
The bundles are split so that useLoginStatusCookie
is in my main bundle (the first bundle to load), and the useSomeData
function isn't called until a subsequent bundle.
However, when I inspect the bundle content with Webpack Bundle Analyzer, I see that the entire content of queries.tsx
and dataRefs.tsx
is loaded in the initial bundle.
How do I import only a single exported function in create-react-app so that the entire file isn't pulled in to my bundle?
I eventually solved this by putting each function in a separate file.