uokersam
uokersam

Reputation: 43

How can i use sass variables from json file?

I need to use variables from options.json in .sass files and .twig templates with gulp. For twig all works great just with

pipe(data(function(file) {
    return JSON.parse(fs.readFileSync('app/options.json'));
}))
.pipe(twig())

But with sass there is a problem, that I cannot solve.

I've found some similar questions, but for Ruby version. Also this gulp plugins doesn't fit because of link in json file:

My json file looks like this:

{
  "page": {
    "view": "mockup",
    "bg": "gradient",
    "buttons": "two"
  },
  "sass": {
    "bgOpacity": ".5",
    "bgPicture": "https://pics.freeartbackgrounds.com/midle/Street_in_Lund_Sweden_Background-1287.jpg",
    "bgColor": "$gradient-4"
  }
}

What I'm trying to do is to use just part of json variables in sass file like this:

$opacity: $sass-bgOpacity;

Is this possible? Maybe there is another way, I just want to theme my entire site (.twig templates, sass variables) from one options.json file.

Very grateful for your help.

P.S. I'm not very good at English language so feel free to correct me.

Upvotes: 2

Views: 5970

Answers (1)

Amir
Amir

Reputation: 1905

Have you tried node-sass-json-importer? It imports a json file into your sass, and you can access the variables with syntax like sass-variables. It hooks into node-sass's importer api.

Here is an example:

style.scss

@import 'some.json'

body {
    font-size: $font_size_in_json
}

some.json

{
    "font_size_in_json": "12px"
}

gulpfile.js

gulp.src('source/**/*.scss')
    .pipe(sassImportJson({'isScss': true, 'cache': false}))
    .pipe(sass())
    .pipe(gulp.dest('dist/resources/css'))

Upvotes: 4

Related Questions