11ty / eleventy-plugin-bundle

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

Nested bundles use-case #20

Open chriskirknielsen opened 5 months ago

chriskirknielsen commented 5 months ago

Hi! I am really enjoying these little bundles of joy.

I'm rebuilding a site and wanted to take advantage of this plugin. I have some one-off layouts for which the <head> content is different in terms of styles and scripts, and various tags (say <link>), so I can adjust what goes in the template for the head (lots of common tags like the title, icon, meta… justify not having duplicated files).

Here's my very simple <head> template:

<!-- parts/head.njk -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title | safe }}</title>

{% getBundle "html", "head" %}

Now, here's my default base.njk layout:

<!-- base.njk -->
<!doctype html>
<html lang="en">
    <head>
        {% html "head" %}
        <script>
            {% js "head" %}{% include "assets/js/global.js" %}{% endjs %}
            {% getBundle "js", "head" %}
        </script>
        <style>{% getBundle "css", "head" %}</style>        
        <link rel="alternate" type="application/rss+xml" title="{{ metadata.title }}" href="{{ metadata.rssUrl }}">
        {% endhtml %}
        <!-- This bundle would then be injected below -->
        {% include "parts/head.njk" %}
    </head>
    <body>
        <header> ...

And with my one-off template, I could use it like this:

<!-- one-off.njk -->
<!doctype html>
<html lang="en">
    <head>
        {% html 'head' %}
        <script>document.documentElement.classList.remove('no-js')</script>
        <style>
            {% css "one-off" %}{% include "assets/css/one-off.css" %}{% endcss %}
            {% getBundle "css", "one-off" %}
        </style>
        <link rel="preload" href="{{ page.data.font.path }}" as="font" type="font/woff2" crossorigin>
        {% endhtml %}

        {% include "parts/head.njk" %}
    </head>
    <body>
        <main>

The reason I can't reuse the very same setup is due to the fact I run PurgeCSS as a transform, and I cache my bundles, so they are reused across the site if the name is identical. I could use a unique bundle name (head-base', 'head-one-off'…) for my JS and CSS per layout but that seems a little gross and not scalable to add them in there. (I need scalability for my 3 layouts, of course 🙃)

I did try to see if it worked and while every element built out as I expected, the contents of those CSS and JS elements were a comment which I assume is replaced by a transform after the fact.

Currently I've worked around the problem by assigning {% block head %}{% endblock %} in my head.njk file and replace the {% html "head" %} with {% block head %}. That works fine in my case, but just wanted to make sure I reported a valid use-case regardless (well, valid enough in my eyes, perhaps!).

Thank you!