connexo connexo - 3 months ago 7
Node.js Question

How to generate an SCSS file from a string in memory using gulp.js?

I would like to generate an scss file containing variable definitions from a JSON file. I am able to read the JSON file into a Javascript variable containing an object.

var colors = {
"primary-color": "#1d1d1b",
"secondary-color": "#558ed5",
"brand-color-a": "#1d446f",
"brand-color-b": "#9b9b99"
}


What I would like to generate from this is an file containing

$primary-color: #1d1d1b;
$secondary-color: #558ed5;
$brand-color-a: #1d446f;
$brand-color-c: #9b9b99;


So I am assuming I first need a function that does the creation of the string:

var scssString = "";
function transformJSONtoSCSS(colors) {
Object.keys(colors).forEach(function(key) {
var value = colors[key];
scssString += "$" + key + ": " + value + ";\n";
}
return scssString;
});


What I need now is the ability to write this String to a file called
_colors.scss
in a directory I'd like to specify.

I have no clue whatsoever how to achieve this with which we are already using. I'm assuming though that this is probably a fairly easy task. Can anyone please push me in the right direction?

Also, what sort of line-endings will
\n
result in in the file being generated?

Edit: I need to integrate this as a gulp task into our watch task. Also, I need to assure that this file generation task is being accomplished before SCSS is then processed to generate the CSS from it.

Answer

As noted in the comments, you don't really need Gulp. However, you can integrate the solution into your gulp watch task quite easily. I whipped up a quick example demonstrating this below:

var fs = require('fs');

var colors = {
    "primary-color": "#1d1d1b",
    "secondary-color": "#558ed5",
    "brand-color-a": "#1d446f",
    "brand-color-b": "#9b9b99"
}

function transformJSONtoSCSS(colors) {
  var scssString;
  Object.keys(colors).forEach(function(key) {
    var value = colors[key];
    scssString += "$" + key + ": " + value + ";\n";
  }
  return scssString;
}

gulp.task('color_scss', function() {
  var scssString = transformJSONtoSCSS(colors);
  fs.writeFileSync("/my/dir/path/_colors.scss", scssString); 
});

// Our watch task - notice our deps.
gulp.task('css:watch', ['css', 'color_scss'], function() { gulp.watch("assets/**/*.css", ['css'])});