首页 > 解决方案 > 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.

标签: jsonsassgulp

解决方案


你试过node-sass-json-importer吗?它将一个 json 文件导入到您的 sass 中,您可以使用 sass-variables 之类的语法访问变量。它连接到node-sass的导入器 api。

这是一个例子:

样式.scss

@import 'some.json'

body {
    font-size: $font_size_in_json
}

一些.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'))

推荐阅读