【问题标题】:Load variables into LESS CSS preprocessor from JSON file从 JSON 文件将变量加载到 LESS CSS 预处理器中
【发布时间】:2013-10-15 15:27:53
【问题描述】:

是否可以像使用 Stylus 一样从 JSON 文件将变量加载到 LESS CSS 预处理器中?

包含文件myvars.json的内容

{
    "color1": "#112345",
    "color2": "#667890"
}

我在 Stylus 中...

json('myvars.json')
body{ background-color: color1; }

是否可以在 LESS 中做到这一点?

我想将文件保存为 JSON,以便我可以轻松地在 javascript 中重复使用它。

【问题讨论】:

    标签: javascript css json less stylus


    【解决方案1】:

    在 less.js 中,您可以使用 javascript 插值(使用反引号)。并调用一个函数,该函数使用文件中的变量加载 json 对象......您可以通过它的键从中提取变量 - 也许是这个方向的东西:

    @json_file: myvars.json;
    
    @json: ~`json = function($key) { var request = new XMLHttpRequest(); request.open("GET", "@{json_file}", false); request.send(null); var my_json = JSON.parse(request.responseText); return my_json[$key]; }`;
    
    body {
      background-color: ~`json('color1')`;
    }
    

    这可能看起来不太优雅,但它确实有效。一个更优雅的选择可能是在 global LESS object before calling the script 中定义您的自定义用户函数,但我从来没有真正打扰过它,因为我总是在开发中使用 LESS 客户端。

    您可以做的另一件事是在 javascript 中加载 json 文件(在浏览器中调用 LESS 脚本之后)并使用 less.modifyVars() 函数使用 json 变量重新编译 LESS。你可以在你的 html 中做一些事情(这里我使用纯 JS,但如果你使用 jQuery.getJSON 会更简单):

    <link rel="stylesheet/less" href="style.less" type="text/css">
    <script type="text/javascript">less = { env: "development" };</script>
    <script src="http://rawgithub.com/less/less.js/master/dist/less-1.4.1.min.js" ></script>
    <script type="text/javascript">
        var request = new XMLHttpRequest();
        request.open("GET", "myvars.json", false);
        request.send(null);
        var my_json = JSON.parse(request.responseText);
        less.modifyVars(my_json);
    </script>
    

    在你的 LESS 样式文件中有这样的东西:

    @color1: darkblue; //default value - will get overwritten by .modifyVars()
    
    body {
      background-color: @color1;
    }
    

    另外注意:LESS 中的所有变量名都必须以 at 符号 (@) 开头。但是,json 变量不需要,因为less.modifyVars() 会自动在变量前面加上@ 如果缺少。

    希望这能给你一些想法。可能有更好的方法来做到这一点......但这两种方法对我有用。

    【讨论】:

      【解决方案2】:

      如果你不在浏览器中使用 LESS 而是编译 CSS,我只是发布了一个 gulp 插件来完成这项工作。

      它可能看起来像这样:

      css/myvars.json

      {
          "color1": "#112345",
          "color2": "#667890"
      }
      

      less/styles.less

      @json-import "myvars.json";
      
      body {
        background-color: @color1;
      }
      

      gulpfile.js

      var gulp = require('gulp');
      var less = require('gulp-less');
      var lessJsonImport = require('gulp-less-json-import');
      
      gulp.task('less', function(){ 
        gulp.src(['./less/**/*.less', '!./less/**/_*.less'])
            .pipe(lessJsonImport())
            .pipe(less())
            .pipe(gulp.dest('./css'));
      });
      

      【讨论】:

        【解决方案3】:

        在浏览器中使用 LESS 时,还有 'globalVars' 选项可用于在加载 LESS 文件之前设置变量:http://lesscss.org/usage/#using-less-in-the-browser-options

        【讨论】:

          【解决方案4】:

          您可以使用globalVarsless 选项来提供从 json 文件加载的对象。

          例如使用 less-loader 插件 webpack.config.js 会像:

          function lessGlobalVars() {
              return require('flat')(require('./path/to/config.json'),
                  {
                      delimiter: '_'
                  });
          }
          
          module.exports = {
            module: {
              rules: [
                {
                  test: /\.less$/,
                  use: [
                    {
                      loader: 'style-loader',
                    },
                    {
                      loader: 'css-loader',
                    },
                    {
                      loader: 'less-loader',
                      options: {
                        globalVars: lessGlobalVars()
                      }
                    }
                  ]
                }
              ]
            }
          };
          

          config.json:

          {
            "dimensions": {
              "width": 100,
              "height": 50
            }
          }
          

          globalVars 只接受平面结构,所以我们需要 flat 包,它将用 require('./path/to/config.json') 加载的对象展平为:

          {
            dimensions_width: 100,
            dimensions_height: 50
          }
          

          将此对象传递给globalVars 选项将使全局变量@dimensions_width 和@dimensions_height 可用于所有less 样式表:

          .some-class {
            width: @dimensions_width;
            height: @dimensions_height;
          }
          

          【讨论】:

            【解决方案5】:

            描述了一种相对较新的方法here:

            myPluginFile.js:

            const axios = require('axios').default
            
            module.exports = {
              install: function (less, pluginManager, functions) {
                functions.add("blue", function () {
            
                  const headers = {
                    'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json',
                    timestamp: +new Date(),
                  }  
                  
                  try {
                    const method = 'get'
                    const url = 'https://myAPI.com/myFile.json'
                    const options = { headers: { ...headers } }
                    const { data } = await axios[method](url, {}, options)
                    return data
                  } catch (error) {
                    console.info('Error', { msg: error.message })
                  }
                });
              },
            };
            

            myStyleFile.less:

            @plugin "myPluginFile";
            
            /* Style the body */
            body {
              color: blue();
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-12-21
              • 1970-01-01
              • 2013-01-07
              • 2011-01-11
              • 1970-01-01
              • 1970-01-01
              • 2010-09-13
              相关资源
              最近更新 更多