Posted 25 days ago. Visible to the public.

Webpacker: Loading code on demand

Sometimes you want to load code on demand. For instance, when a a large library is only used on a single screen, this library should only be loaded for that screen. It should not blow up the bundle size for all screens.

You can load code on demand by using import() as a function (with parentheses) instead of using it as a keyword import (without parentheses). The import() function returns a promise with the exported variables:

let exports = await import('large-library') console.log("A named export is ", exports.exportedName) console.log("Default export is ", exports.default)

Webpack will build a new .js file for the code that is loaded on-demand:

public/ packs/ application-b1762adc0d6538318dec.js # your pack 0-d15ee844981f2f70c164.chunk.js # the dynamically generated chunk

Note that the chunk is created automatically by Webpack. You don't need to manually create a new pack.

Because the chunk is loaded into an existing Webpack environment, it contains less boilerplate (for the Webpack module registry etc.) than a pack.

Learn more

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Henning Koch
Last edit:
21 days ago
by Henning Koch
code, splitting, dynamic, import, function, lazy, load
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more