A CSS minifier built with Ruby — Work in progress.
- Combine selectors. (This will probably reduce the code more than anything else, so it has to be done really good.)
- Optimize unnecessary specific selectors. E.g.
body div #idto#id. Also remove the universal selector when it's not needed, e.g.:*.classto.class. - Combine properties into shorthand properties if possible. (E.g.
margin-top,margin-right,margin-bottomandmargin-leftintomargin.) - Remove all whitespace characters and
/* */comments if they are not inside a string. This will be done automatically because of the way the CSS is parsed and rearranged. - Omit the last semicolon as it's optional.
- Replace
noneand0followed by a suffix (px,emand so on) with0as they do the same thing. - Replace the
font-weightvaluesnormalandboldwith their corresponding numeric values400and700. - Replace
rgb,hsl,rgba/hslawith1as the alpha value,cymkand the color keywords if they are longer than 4 or 7 characters with their corresponding HEX values. Use the color keywords if they are shorter than the corresponding HEX values. (E.g.redinstead of#f00.) - Use shorthand HEX values if possible. (
#f80instead of#ff8800.)
require 'comprecssor'
compiler = comprecssor.new
compiler.minify('The CSS in a string', {}); # CSS in a string
file = File.open('file.css')
compiler.minify(file); # CSS in a file
file2 = File.open('file2.css')
compiler.minify([file, file2]) # Two CSS files
compiler.minify(file, {}) # Options in a hash// Parser output:
{
'at-rules' => {
'charset' => '',
'media' => [
{ 'conditions' => [], 'rules' => {} },
],
'import' => [
{ 'url' => '', 'conditions': [] }
],
'page': [
{ 'selector' => '', 'rules' => {} }
],
'font-face': [
{ rules => {} }
],
'namespace' => [], # ?
'keyframe' => [
{ 'name' => '', 'rules' => {} }
]
},
'rules' => {
'key:selector' => {
'property' => 'value'
}
}
}Parsing h1 { color: red; } should return a rules hash:
{
'h1' => {
'color' = 'red'
}
}If you've found any bugs or have suggestions, let us know!
Or if you want, you can fork this project on GitHub and create a pull request.
Authors:
Florian H.
Mogria m0gr14@gmail.com
License:
MIT, see LICENSE