Skip to content

Instantly share code, notes, and snippets.

@chriseppstein
Last active November 26, 2019 07:40
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseppstein/7951379 to your computer and use it in GitHub Desktop.
Save chriseppstein/7951379 to your computer and use it in GitHub Desktop.
compiling a minified version of css. This configures your compass project to emit files in minified form when compiling for production.
$ compass compile --environment production && compass compile

Afterwards you will have both the minified and non-minified versions in your output folder. Note that compass clean will not clean up your minified files.

# add this to your compass configuration file
extend Compass::Actions
Compass::Logger::ACTION_COLORS[:move] = :green
# Relativizing a path requires us to specify the working path.
def working_path
Dir.pwd
end
# you can change how a minified filename is constructed by changing this function.
# note that currently, chrome only understands sourcemaps that end in .css.map
def min_name(name)
dir = File.dirname(name)
base = File.basename(name)
base, ext = base.split(".", 2)
if dir == "."
"#{base}-min.#{ext}"
else
File.join(dir, "#{base}-min.#{ext}")
end
end
on_stylesheet_saved do |css_file|
if top_level.environment == :production
min = min_name(css_file)
FileUtils.mv css_file, min
css = File.read(min)
changed = false
# if there's a sourcemap, it is also moved.
css.gsub!(%r{sourceMappingURL=(.*) ?\*/}) do |match|
changed = true
"sourceMappingURL=#{min_name($1)} */"
end
if changed
open(min, "w") do |f|
f.write(css)
end
end
logger.record :move, "#{relativize(css_file)} => #{relativize(min)}"
end
end
# this is new in compass 1.0.0.alpha.18
on_sourcemap_saved do |sourcemap_file|
if top_level.environment == :production
min = min_name(sourcemap_file)
FileUtils.mv sourcemap_file, min
logger.record :move, "#{relativize(sourcemap_file)} => #{relativize(min)}"
end
end
@bpainter
Copy link

Magical. I was trying to get something like this to work earlier this week. You have good timing.

@boldfacedesign
Copy link

Excellent. I had been trying to build this kind of functionality into my fork https://github.com/boldfacedesign/compass but couldn't get the watch function to work properly. This opens some new options for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment