certainlyakey
3/9/2015 - 2:39 PM

Checking environment in (node) Sass

Checking environment in (node) Sass

$ENV: "development" !default;

//usage example: I want to show/hide responsive helper from sass-mq depending on env
@if ($ENV == "development") {
    $mq-show-breakpoints: (mobile, mobileLandscape, tablet, desktop, wide);
}

//this would be in the sass-mq file
$mq-show-breakpoints: () !default;

@debug("current env is " + $ENV + ", meaning $mq-show-breakpoints is \"" + $mq-show-breakpoints + "\"");

Environment variable in Sass with node-sass

Having some sort of env variable is possible with Ruby Sass through custom functions.

node-sass doesn't have that (yet) though, but that doesn't keep us from doing what we want.

Here is an example. In the JavaScript script, we check for SASS_ENV presence and change the Sass $ENV variable accordingly.

If you use sass-mq, this is useful to toggle the helper:

$ export SASS_ENV=development && node compile
variables.scss:11: DEBUG: current env is development, meaning $mq-show-breakpoints is "mobile, mobileLandscape, tablet, desktop, wide"


$ export SASS_ENV=production && node compile
stdin:12: DEBUG: current env is production, meaning $mq-show-breakpoints is ""
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
var ENV = process.env.SASS_ENV || 'development';

var file = 'variables.scss';

//if in dev, directly pass file to sass
if (ENV === "development") {
  return sass.render({ file: file });
}

//if not, get file data and add $ENV variable in Sass before compiling
fs.readFile(file, function(err, data) {
  sass.render({
    data: "$ENV: \"" + ENV + "\";\n" + data,
    includePaths: [ path.dirname(file) ]
  });
});