Thursday 12 September 2019

Checking if a module is already loaded in Webpack?

I worked at a company that has a custom JS module bundler. The implementation has a function requireIfLoaded that allows you to require a module, but only if it has already been loaded. If the module isn't loaded yet, it throws an error. Using requireIfLoaded doesn't bundle the module. This drastically reduced our file size.

Here's an example of how it can be useful:

if (page === PROFILE) {
  // ProfileHelper should already be downloaded if we're on the profile page.
  const ProfileHelper = requireIfLoaded('ProfileHelper');
  ProfileHelper.doSomething();
} else if (page === FEED) {
  // FeedHelper should already be downloaded if we're on the feed page.
  const FeedHelper = requireIfLoaded('FeedHelper');
  FeedHelper.doSomething();
}

A separate bundle is generated for the profile page and for the feed page. require('ProfileHelper') isn't called in the feed page codepaths, so ProfileHelper isn't included in the feed bundle. require('FeedHelper') isn't called in the profile page codepaths, so FeedHelper isn't included in the profile bundle. Does Webpack have something like this?

There's a potential solution here: https://github.com/webpack/webpack/issues/526

However, this was from 2 years ago and the code looks pretty hacky. Is there a better way? If this is still the best way, let me know via an answer and I will mark it as the correct answer.

Edit for clarification:

If I required both ProfileHelper and FeedHelper all the time, then one of the modules will be unused. At most one of them is loaded on any given page. On the profile page, ProfileHelper is loaded, but not FeedHelper. Vice-versa for the feed page.

Also, I don't want to use require.ensure because it's async.



from Checking if a module is already loaded in Webpack?

No comments:

Post a Comment