Swaagie / minimize

Minimize HTML
MIT License
163 stars 18 forks source link

Better explanation of how plugins work #44

Closed voor closed 9 years ago

voor commented 9 years ago

Hi, I wanted to try and use a plugin to "skip" certain elements. Specifically, elements that might later on be changed by server-side rendered code.

For example, I use ejs in Express so my error page has an element <%= error %> that I want to ignore during minimize. I have the following plugin:

  plugins: [{
      id: 'ejs',
      element: function element(node, next) {
        if (node.name === '%=') {
          // Ignore further processing
        }
        next();
      }
    }]

That can detect the elements, but there doesn't seem to be a way to say "skip ahead and don't process these"

Swaagie commented 9 years ago

Totally agree on the documentation part, will improve on that this weekend.

The issue your describing is more related to the inner workings of the htmlparser2 though. It minifies HTML, not HTML templates. The problem is that htmlparser2 will see the <> of ejs as an element, while it actually is not. Basically you want minimize to parse your compiled templates, e.g. the output <%= error %>.

As far skipping, you should be able to simply call the next callback, e.g. if (node.name === '%=') next();. While traversing the DOM each element is simply handed of to your plugins as this allows maximum flexibility.

voor commented 9 years ago

While the next(); callback will avoid processing it further in the plugin, the end result is still an output of:

Goes in:

<%= error %>

Comes out:

<%= error="" %=""></%=>
Swaagie commented 9 years ago

This is beyond plugin scope. The dependency htmlparser2 will parse the HTML template and parses the <%= error %> as an element. As you can see in your output the last % is parsed to %="" (e.g. sparse attribute), as if it would be an HTML element which it is clearly not. Minimize should simply be called after the templates are rendered. This is even more optimal as it will also minify the generated/inserted HTML.

Closing this issue for now, allowing plugins to do something that is beyond the scope of this module does not make a lot of sense