Skip to content

Instantly share code, notes, and snippets.

@erkie
Last active October 20, 2016 08:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkie/7bf2069d6f5c5b11d001 to your computer and use it in GitHub Desktop.
Save erkie/7bf2069d6f5c5b11d001 to your computer and use it in GitHub Desktop.
Convert less to sass

Convert .less files to .scss

To run:

cd root-directory-of-project/
ruby less-to-sass.rb

# or
ruby less-to-sass.rb <file-glob-to-convert>

Warning: This will delete the .less files it converts and replace them with .scss equivalents

Things this script doesn't do:

  1. Convert mixins with when-directives
  2. Simply removes quotes on ~"unescaped" strings
  3. Convert class-like mixins .foo { } .bar { .foo(); }
  4. Some more minor bugs

sass

#!/usr/bin/env ruby
file_pattern = ARGV[0] || "**/*.less"
puts "Converting #{file_pattern} in current directory"
def convert_file(file)
contents = open(file).read
contents = convert_string_tildes contents
contents = convert_string_interpolations contents
contents = convert_variables contents
contents = convert_mixins contents
contents = convert_media_queries contents
write_sass file, contents
end
def convert_variables(less)
less.gsub /@((?!media|include|import|font-face|-moz-keyframes|-webkit-keyframes|keyframes|-o-keyframes)[a-zA-Z_]*)/, '$\1'
end
def convert_mixins(less)
less.gsub(/^(\s*)\.([^(;]+\([^)]*\)\W*\{)/, '\1@mixin \2')
.gsub(/^(\s*)[.#]([^(;{]*\(.*\)\W*;)/, '\1@include \2')
end
def convert_media_queries(less)
less.gsub(/@media \$([^{]*)/, '@include media-\1')
end
def convert_string_interpolations(less)
less.gsub(/\@\{([^}]*)\}/, '#{@\1}')
end
def convert_string_tildes(less)
less.gsub(/~"([^"]*)"/, '\1')
end
def write_sass(file_name, sass)
File.open(file_name.gsub(/\.less$/, '.scss'), 'w') do |f|
f.write sass
puts "Wrote #{file_name}"
end
File.delete file_name
end
files = Dir.glob(file_pattern)
files.each do |file|
convert_file file
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment