Halo-Lab / eleventy-packages

Monorepo for all Eleventy plugins.
24 stars 1 forks source link

[eleventy-plugin-compress] Empty brotli file #42

Closed eitchtee closed 1 year ago

eitchtee commented 1 year ago

Hi there,

I've stumbled upon a very weird bug.

In my setup I have a .njk file that includes a JS script so I'm able to minify these files within Eleventy using a transform, without needing other tools

---
permalink: /js/testing.js
---
{% include "scripts/testing.js" %}

And these javascript files are them added to my layout based on a condition set on the front matter

{% if enable.testing %}
  <script src="/js/testing.js"></script>
{% endif %}
---
layout: "default"
enable:
    testing: true

permalink: /bug/
---

I've not been able to pinpoint exactly what causes the problem, but when building my site I get a broken brotli file with ; as it's only content.

I've setup a minimal example to help debug. demo.zip


A few things worth noting:

Olezhka-web commented 1 year ago

Hello @eitchtee . Thank you for contacting us.

The problem is that you create the js script through eleventy, and eleventy writes the files after all the plugins have worked.

That is, the situation arises, the first time you build, the file has not yet been created and an error occurs. And for the second build, the file will already be there - that's why there is no error for the second build. Accordingly, in relation to this information, the content will also be recorded incorrectly.

Do you really need to create a js file through njk as an eleventy template ?

If you are not critical, then you can not use templates for generating files that will be compressed yet.

eitchtee commented 1 year ago

I suppose this is a precedence problem, something like the layout that uses the js file is built, the plugins tries to compress the scripts mentioned in this layout, which doesn't exist at the time, and them 11ty builds the js file from the template (too late now), right?

The hack for building the js files from a njk template came from here https://github.com/11ty/eleventy/issues/344#issuecomment-485019492, as at the time I needed a way for 11ty to process the files for a custom transform that minified it, as a PassthroughCopy wouldn't allow me to do it. After some research I found a way of doing it within the addPassthroughCopy function.

  eleventyConfig.addPassthroughCopy(
    "./src/js/*.js",
    {
      transform: (src, dest, stats) => {
        return new Transform({
          transform(chunk, enc, done) {
            done(null, minjs(chunk.toString()));
          }, }); }, } );

Which, at least from my tests, seems to have completely fixed the problem.


Not sure if possible, but perhaps the plugin could attach to eleventy.after, running only after everything is properly built. Food for thought.

Thank you very much for taking the time to reply and great work!