I have come up with this solution using line-reader:
var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");
var fs = require('fs');
// read a file line-by-line
var lineReader = require('line-reader');
gulp.task('default', function () {
var myVar;
var re;
var s = ""; // will build up temp file with this variable
fs.readFile('variabales.scss', 'utf8', function (err, contents) {
// e.g., assumes a single line format like $color: #009999;
// myVar will = $color
myVar = contents.split(/:/)[0].trim();
// want to include lines that have a {, } or @ symbol on them
// as well as the $___ sass variable
re = new RegExp('(\\' + myVar + ')|{|}|@');
});
var readStream = fs.createReadStream('app.scss');
lineReader.eachLine(readStream, function(line, last) {
if (line.match( re )) {
s += line + "\n";
}
if (last) {
fs.writeFileSync('temp.scss', s);
gulp.src("temp.scss")
// gulp-sass gets rid of the empty ruleset automatically!
.pipe(sass().on('error', sass.logError))
.pipe(rename('app.css'))
.pipe(gulp.dest('./'));
return false; // stop reading
}
})
});
Your app.scssfile should have an import statement at the very top like:
@import "variabales.scss";
.button{
color : $color;
}
.background{
background : $color;
padding : 10px;
}
.element{
margin : 0 auto;
}
So Sass can retrieve the variable from variabales.scss.
No doubt this could be improved by writing to a buffer instead of to a temp file or directly to a stream.
If you wanted your final app.css file to have more sass variables in it than just one, you could generalize this by modifying the regexp to match on "$" instead of the specific "$color".
re = new RegExp('[\\${}@]');
And then you could rid of the fs. readFile call.
Here is the resulting app.css file:
.button {
color: #009999; }
.background {
background: #009999; }