Skip to content

Instantly share code, notes, and snippets.

@manuhabitela
Last active September 4, 2019 08:51
Show Gist options
  • Select an option

  • Save manuhabitela/a9f125406c1efd916448 to your computer and use it in GitHub Desktop.

Select an option

Save manuhabitela/a9f125406c1efd916448 to your computer and use it in GitHub Desktop.
Checking environment in (node) Sass

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) ]
});
});
$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 + "\"");
@roppa
Copy link
Copy Markdown

roppa commented Sep 20, 2018

Excellent, thanks for sharing!

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