This line of code is expensive to run:
require(`./path/to/large_file`)
Without it, the React app build bundle resulted in 36 MB.
With it, it resulted in 92 MB.
The above line of code is run during initiation.
I tried to lazy load it by instead return this:
function lazy_loader() {
return () => require(`./path/to/large_file`)
}
And during initiation, I the instead only runs:
lazy_loader();
lazy_loader()
only returns a function, which will require the large_file
if run.
However, this actually made no difference at all.
The build bundle size is still 92 MB.
Can someone explain why this didn’t help?
And if possible what I can do to fix this?
2
Answers
./path/to/large_file
is indeed only imported duringlazy_loader()
. But the imported file must be included in the bundle too, otherwise how can it be found when importing?Dynamic importing is mainly used in modern Web development to avoid producing unnecessary traffic (e.g. loading pages). In your case, I think you can directly 7z-compress the latge file and decompress it in the program.
Unfortunately your „lazy loading“ is not detected by Webpack (which I assume you use to bundle) – Try to use a dynamic
import(…)
as documented:Note that lazy_loader now returns a Promise (as fetching the additional code via network might take some time).