Skip to content

Component bundling

Xander Marjoram edited this page Nov 6, 2023 · 5 revisions

Note

This section is a work in progress.


The bundling of components can be complicated, especially when there are nested layers of dependencies. Here is a simple example of how a component may consume other components but also be consumed by another.

graph LR;
    pie-cookie-banner --> pie-modal; pie-cookie-banner --> pie-button; pie-cookie-banner --> pie-icon-button;
    pie-modal --> pie-button; pie-modal --> pie-icon-button;

    style pie-modal fill:#33c, stroke:#aaa, stroke-width:2px;
Loading

This raises questions around how packages are bundled. If the output files for pie-modal and pie-cookie-banner also contained the bundled pie-button and pie-icon-button, then pie-cookie-banner would likely include them twice! This is undesirable because it will lead to package bloat which causes degraded performance for consumers of the library.

Our proposed strategy is as follows:

  • When one component depends on another, add it to dependencies (rather than peerDependencies or devDependencies).
    • This tells the package manager that this package should be included in node_modules, along with any of its dependencies.
  • Make sure you import the component, e.g., import '@justeattakeaway/pie-button';.
    • This has the desired side-effect of registering the component in the browser as a custom element.
  • Tell rollup not to include other components in the bundle.
    • We can use a regex to define all @justeattakeaway packages as external.
  • Now, if you were to install pie-modal and pie-button into your website, you would see that both work as expected, both individually and together.
    • In the console there should not be a message warning you about trying to register a component multiple times, because the browser is clever enough to not import the module again unnecessarily. This can be confirmed by looking in the Network tab in the browser's dev tools, where you will see pie-button fetched only once.