skip to Main Content

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


  1. ./path/to/large_file is indeed only imported during lazy_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.

    Login or Signup to reply.
  2. Unfortunately your „lazy loading“ is not detected by Webpack (which I assume you use to bundle) – Try to use a dynamic import(…) as documented:

    function lazy_loader() {
      return () => import(`./path/to/large_file`)
    }
    

    Note that lazy_loader now returns a Promise (as fetching the additional code via network might take some time).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search