Line comments make debugging Sass a breeze!

In response to my recent article about Sass, a couple of folks have asked about how easy it is to debug. The question is a good one.

If Sass is generating your CSS this adds another layer of complexity that you must deal with when something goes wrong. If you use tools like FireBug, you can easily inspect an element and see the line number where a particular style was defined. But if you are using Sass, how can you tell the line number of the rule in your source file if the generated CSS file bears little resemblance to your Sass file?

As it turns out, Sass actually has a solution for this. If you set the :line_comments option to true the generated output will contain the line number and source file where each rule was defined.

The output looks something like this for each rule:

/* line 20, sass/_reset.sass */
body {
  line-height: 1;
  color: black;
  background: white;

Here’s my Sass initialization file that I use with Rails to ensure that this only happens in development mode. Drop this in config/initializers/sass.rb:

require 'sass' if /production|staging/.match(RAILS_ENV) # Compress CSS (a small file is preferable in production) Sass::Plugin.options[:style] = :compressed else # Expand CSS Sass::Plugin.options[:style] = :expanded # Generate CSS from SASS every time a controller is accessed Sass::Plugin.options[:always_update] = true # Insert comments in the CSS about the line numbers of the Sass source Sass::Plugin.options[:line_comments] = true end

Note that the Sass Reference currently claims that the key to enable this behavior is :line_numbers, but this is wrong. The correct key name is :line_comments. I suspect that they are updating the docs as we speak.

© 2013 John W. Long