Ever wanted to make your own CSS2Sass convertor ? When working on projects, a tool that can quickly convert our CSS code to Sass can be ridiculously useful. Let’s see how to do it.
Using sass-convert
The Sass Ruby Gem ships with a sass-convert executable. Its quite funny that many people still do not know about it or get confused thinking that its for SCSS -> Sass and Sass -> SCSS conversion. Well, after all SCSS is CSS, right ?
This command will help you convert your CSS code to Sass or SCSS:
[shell]
sass-convert style.css style.sass
sass-convert style.css style.scss
[/shell]
style.css should be an existing CSS file, while style.sass and style.scss files will be generated if they don’t exist.
In Ruby Code
I quickly dig into the sass gem and tried to figure out what sass-convert basically does, so that one could also implement the exact same functionality in plain Ruby Code (it can be really useful sometimes). Here’s what I came up with:
[ruby]
require ‘sass/css’
# CSS Code
css = %Q{
body {
color: red;
}
}
# SASS
puts ::Sass::CSS.new(css).render(:sass)
# SCSS
puts ::Sass::CSS.new(css).render(:scss)
[/ruby]
Downsides
If I am not wrong, I don’t think the conversion preserves any variables, mixins, inheritance, etc. Although nesting is added appropriately. So, the result might not be spot on always, but can still be a time saver sometimes.