This PostHTML plugin minifies classnames and ids, reducing the weight of your HTML.
npm i -D posthtml-minify-classnames
import posthtml from 'posthtml'
import minify from 'posthtml-minify-classnames'
const html = `
<style>
#foo { color: red }
.bar { color: blue }
.baz { transition: all }
.biz { color: green }
</style>
<div
id="foo"
class="bar"
x-transition:enter="baz"
x-transition:enter-start="biz"
>baz</div>`
posthtml()
.use(minify({
filter: /^.bar/,
genNameClass: 'genNameEmoji',
genNameId: 'genNameEmoji',
customAttributes: ['x-transition:enter'],
}))
.process(html)
.then(result => {
console.log(result.html)
})
Result:
<style>
#a { color: red }
.bar { color: blue }
.b { transition: all }
.biz { color: green }
</style>
<div
id="a"
class="bar"
x-transition:enter="b"
x-transition:enter-start="biz"
>baz</div>
To use with external stylesheets, other plugins must be used, like posthtml-inline-assets and posthtml-style-to-file, or other build task plugins.
You may use an options object to configure the plugin.
Type: RegExp
Default: /^.js-/
Define a regular expression that will be used to exclude names from processing.
Classes and IDs that match this will not be minified.
Type: Boolean|String
Default: 'genName'
The name generator to use for classes and IDs.
Possible values:
'genName'
- generates the smallest possible names'genNameEmoji'
- generates small emoji based names'genNameEmojiString'
- generates random emoji with 3 emojis in eachfalse
- preserves names, use this to ignore ids or classes
While emoji visually looks like a great way to reduce the size of input values, they often use 3-4 bytes or more (some can be over 20 bytes for a single rendered glyph). The below example 3 emoji string values range between 10-12 bytes in size, that's equivalent to ASCII strings up to 12 characters long.
Meanwhile base36(0-9,a-z
) provides an "alphabet" of 36 characters and an equivalent length of 3 characters is more than enough for most users (36^3 = 46656
).
Type: String[]
Default: []
An array of strings containing custom attribute names that will have their values minified.
Type: Boolean
Default: true
Whether to remove classes, attributes and other identifiers from the HTML that are not defined in the CSS.
Currently this only works for values in HTML attributes, it does not remove unused selectors from the CSS.