11ty / eleventy-plugin-bundle

Little bundles of code, little bundles of joy.
70 stars 3 forks source link

Hoist duplicated (non-`default`) buckets (in `css` and `js`) to `default` bucket #5

Closed zachleat closed 1 year ago

zachleat commented 1 year ago

Say this island exists in two separate independent sections of a WebC page:

<is-land on:visible webc:bucket="my-bucket">
    <style webc:keep @raw="getBundle('css', 'my-bucket')"></style>

    <template data-island="once">
        <script type="module" webc:keep :src="getBundleFileUrl('js', 'my-bucket')"></script>
    </template>

    <image-compare-defined></image-compare-defined>
</is-land>

Note that this means the same bucket CSS will exist in two places on the page <style webc:keep @raw="getBundle('css', 'my-bucket')"></style>.

More simply, what should happen when we output the same non-default bundle twice?

<style webc:keep @raw="getBundle('css', 'my-bucket')"></style>
<style webc:keep @raw="getBundle('css', 'my-bucket')"></style>

Or

<style webc:keep @raw="getBundle('css', 'my-bucket')"></style>
<link rel="stylesheet" webc:keep :src="getBundleFileUrl('css', 'my-bucket')">

In those cases I’d like to hoist the CSS from the compare-defined bucket into default.

Future versions of WebC will perform this bucket hoisting more intelligently inside of WebC at a component level.

This feature is specifically for the use case when getBundle is called more than once on a single page (or getBundle is used to output the same code as getBundleFileUrl).

Notably, you exclusively use external files (getBundleFileUrl) to workaround this issue too but I think we can do better for getBundle.

zachleat commented 1 year ago

This behavior will be opt-in with the hoistDuplicateBundlesFor option.

Usage:

const bundlerPlugin = require("@11ty/eleventy-plugin-bundle");

module.exports = function(eleventyConfig) {
    eleventyConfig.addPlugin(bundlerPlugin, {
        hoistDuplicateBundlesFor: ["css", "js"],
    });
};
zachleat commented 1 year ago

Shipping with @11ty/eleventy-plugin-bundle v1.0.2