Load variables into LESS CSS preprocessor from JSON file

后端 未结 4 1173
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 04:47

Is it possible to load variables into LESS CSS preprocessor from a JSON file like you can do with Stylus?

With contents of file myvars.json

         


        
4条回答
  •  无人共我
    2021-02-05 05:23

    You can use globalVars less option to provide object loaded from json file.

    For example with less-loader plugin webpack.config.js will be like:

    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 accepts only flat structures so we need flat package that will flatten object loaded with require('./path/to/config.json') to:

    {
      dimensions_width: 100,
      dimensions_height: 50
    }
    

    Passing this object to globalVars option will make global variable @dimensions_width and @dimensions_height available for all your less stylesheets:

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

提交回复
热议问题