terser / html-minifier-terser

actively maintained fork of html-minifier - minify HTML, CSS and JS code using terser - supports ES6 code
https://terser.org/html-minifier-terser
MIT License
385 stars 32 forks source link

Minify JSON-LD #146

Closed atjn closed 1 year ago

atjn commented 1 year ago

Hi there and thanks for this very cool tool :)

It is relatively common for a site to add some form of json-ld metadata for search engines or other web crawlers to use. Here is a basic example for a PWA:

<script type="application/ld+json">
  {
    "@context": "https://schema.org/",
    "@type": "MobileApplication",
    "name": "Fancy App",
    "description": "Does cool stuff",
    "applicationCategory": "Entertainment"
  }
</script>

Currently, html-minifier-terser ignores these scripts, which means whitespace is not removed. I would suggest adding a rule called minifyJSON that takes any script matching type /^application\/(?:\S*\+)?json$/ui, and then removes whitespace with JSON.parse() followed by JSON.stringify().

If you want to be more advanced, there are also json-ld parsers which can theoretically minify the data even more, although I doubt the savings will be very large. For me personally, only removing the whitespace is fine :)

DanielRuf commented 1 year ago

Please see https://github.com/terser/html-minifier-terser/issues/34#issuecomment-1073016429 and the other comments there.

atjn commented 1 year ago

I see, thank you! Although I will note that this is a relatively bad minification method, since it still keeps a lot of the whitespace. It might even add whitespace to some tags. Here is the above script after being minified:

<script type="application/ld+json"> { "@context": "https://schema.org/", "@type": "MobileApplication", "name": "Fancy App", "description": "Does cool stuff", "applicationCategory": "Entertainment" } </script>
DanielRuf commented 1 year ago

Although I will note that this is a relatively bad minification method, since it still keeps a lot of the whitespace. It might even add whitespace to some tags. Here is the above script after being minified:

It may depend on your minifier settings.

grafik

atjn commented 1 year ago

It may depend on your minifier settings.

I gave it a shot, but I can't find any setting that removes the extra whitespace. The example you posted also doesn't remove most of the extra whitespace.

It seems that disabling conservativeCollapse removes the very first and very last whitespace character, as you also show in your example, but that is only a small amount of the whitespace removed.