Search code examples
sasscompass-sass

Is it possible to write (via sass commands or compiler directives) code such that SASS will output the final values of all variables to a JSON file?


How can I compile a SASS file and have it output all the final values of every variable in a json file I asked a similar question before and someone on here thought I was trying to get you guys to do my job. I'm just trying to see if it's possible at all before I go down a path that ultimately is a waste of time. If it is possible, I don't know the magic sauce to get started.

I have CMS themes that are built on bootstrap-sass, and other sass frameworks, and I'd like my CMS to be able to access variables that we use in the SASS files as well. Seems to me that if when I compiled the SAAS file, I got a CSS, MAP, and JSON file, I'd be all set.

I could write this as some kind of mixin, but even then, I'd need to be able to get

  1. A list of all variables
  2. a command to output json to the dist folder.

Any pointers on these items are appreciated.


Solution

  • If you're using Gulp to compile your SASS there is a plugin that accomplishes this.

    https://www.npmjs.com/package/gulp-sass-json

    After installing it, and given the following Gulpfile.js:

    var sassJson = require('gulp-sass-json');
    
    var paths = {
        'json_root' : './bundles/theme/scss/variables/*.scss', 
        'json_dest' : './json'
    };
    
    var sassOptions = {
        errLogToConsole: true,
        outputStyle: 'expanded'
    };
    
    gulp.task('sass-json', function () {
        return gulp
            .src(paths.json_root)
            .pipe(sassJson())
            .pipe(gulp.dest(paths.json_dest));
    });
    
    gulp.task('default', ['sass-json']);
    

    Given the SCSS file variables/colors.scss:

    $red: #ed1414;
    $blue: #0351e0;
    $green: #259208;
    

    Outputs the following json at ./json/colors.json

    {
        "red": "#ed1414",
        "blue": "#0351e0",
        "green": "#259208"
    }
    

    So in order to have it re-output it every time you compile, you can just create a task that encompasses this task as well as your normal style compile task.