Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert Less to Stylus for general purpose
replacements = [
# Remove opening brackers.
[/^(\ *)(.+)\ +\{\ *\n?\ */mg, '$1$2\n$1 '],
[/^(\ *)([^\ \n]+)\ +\{\ *\n?\ */mg, '$1$2\n$1 '],
[/\ *\{\ *\n*/g, '\n'],
# Remove closing brackets.
[/\ *\}\ *\n*/g, '\n'],
# Remove semicolons.
[/\;\ *?$/gm, ''],
# Replace @variable: with $variable =.
[
/@(\w+):(\ *)\ /g, (_, $1, $2) -> "$#{$1}#{$2} = "
],
[/\@(\w+)/g, (_, $1) -> (if $1 == 'import' then _ else "$#{$1}")],
# Replace mixins from .border-radius(4px) to border-radius(4px).
[/\.([\w-]+)\(/g, '$1('],
# Make all commas have 1 space after them.
[/,\ */g, ', '],
[/\.less/g, '.styl'],
[/(\ *)(.+)>\ *([\w-]+)\(/g, '$1$2>\n$1 $3('],
# Need to make sure things like -webkit-background-size are left-aligned
# Need to handle expressions.
[/\/\/.*$/mg, ''], # Remove inline comments.
[/\n+/g, '\n'], # Remove multiple EOL.
[/\ +$/mg, ''], # Remove trailing whitespace.
]
less2stylus = (string) ->
for [pattern, replacement] in replacements
string = string.replace pattern, replacement
lines = string.split('\n')
indent = 0
for line, index in lines
if line.match(/^[^\/]?\ *[\w-\*]+: /) # property name
lines[index] = line.replace(/^\ */, Array(indent + 1).join(' '))
else if line.match(/^\ +[\w-]+\([^\$\)]/) # mixin
line
else if not line.match(/\/{2}/)
indent = line.match(/^(\ *)/)[1].length + 2
if line.match(/e\(\%\(/)
lines[index] = "#{Array(indent + 1).join(' ')}// #{line}"
lines.join('\n')
replaceDirectoryFiles = (root) ->
fs = require 'fs'
sysPath = require 'path'
names = fs.readdirSync root
names.forEach (name) ->
lessCode = fs.readFileSync(sysPath.join root, name).toString()
stylusCode = less2stylus lessCode
stylusPath = sysPath.join root, name.replace(/\.less$/, '.styl')
fs.writeFileSync stylusPath, stylusCode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment