Contact!

@Debug, @Warn and @Error: debugging in Sass

debugging in sass

Programming blind would be a dark and lonely place for any modern developer. Fortunately, Sass has debugging features to make problems easier to work with. With @debug, @warn and @error we can debug useful information straight to our consoles.

It is worth noting that I use node-sass in my examples, so your mileage may vary.

@debug

Ever wondered how to dump a variable in Sass? @debug has you covered. This handy rule allows you to output variables and expressions directly to your console. It even adds the file and line-number for your convenience.

$colour: #fff;

div {
    background: $colour;

    @debug "The colour is: #{$colour}";
}

In this example we are simply dumping the current value of $colour to the console.

/* Console Output */

path/to/style.scss:6 DEBUG: The colour is: #fff

@warn

@warn allows you a form of validation. It doesn’t stop Sass from running but will throw a warning if the code is run. This is a neat way to remind yourself, or your users, of certain stylistic typos or problems.

$background: #fff;
$colour: #fff;

div {
    background: $background;
    color: $colour;

    @if $background == $colour {
        @warn "Background and text are both #{$colour}!";
    }
}

In this example the background colour and text colour are the same, therefore a warning is shown in the console.

/* Console Output */

WARNING: Background and text are both #fff!
         on line 9 of style.scss

@error

Finally we have the meaty ‘hey, stop everything‚Ķ you’ve F***ed up!’ rule. If run, @error will print an error message and then stop the compiler dead.

$background: #fff;
$colour: #fff;

div {
    @if $background == $colour {
        @error "Background and text are both #{$colour}!";
    }

    background: $background;
    color: $colour;
}

The example stops the style sheet from being written and throws an error and stack trace which looks something like this:

/* Console Output */

{
    "status": 1,
    "file": "path/to/file",
    "line": 10,
    "column": 10,
    "message": "Background and text are both #fff",
    "formatted": "Error: Background and text are both #fff\n on line 6 of path/to/file... etc"
}

Join the discussion!

You might like: