Thursday 15 May 2014

gruntjs - Compile LESS to multiple CSS files, based on variable value -



gruntjs - Compile LESS to multiple CSS files, based on variable value -

having single variable specifies color within variables.less file (e.g. @themecolor: #b30f55;), , .json file constitutes list of entities, each key entity id , value of key entity's color (e.g. '8ab834f32' : '#b30f55', '3cc734f31' : '#99981f'), how run grunt task outputs many independent css files there entities in json, after substituting variable value?

you can define different task each color. grunt-contrib-less supports modifyvars option:

modifyvars

type: object default: none

overrides global variables. equivalent --modify-vars='var=value' alternative in less.

you can set modifyvars: themecolor={yourcolor} each task

.json file constitutes list of entities

see: grunt - read json object file

an other illustration can found @ dynamic build processes grunt.js

example

colors.json:

{ "colors" : [ {"color" : "#b30f55", "name" : "8ab834f32"}, {"color" : "#99981f", "name" : "3cc734f31"} ] }

gruntfile.js:

module.exports = function (grunt) { 'use strict'; grunt.initconfig({ pkg: grunt.file.readjson('package.json'), }); grunt.loadnpmtasks('grunt-contrib-less'); var alltaskarray = []; var colors = grunt.file.readjson('colors.json').colors; var tasks = {}; (var color in colors) { var dest = 'dist/css/' + [colors[color].name] + '.css'; tasks[colors[color].name] = {options: { strictmath: true, outputsourcefiles: true, modifyvars: {} },files:{} }; tasks[colors[color].name]['files'][dest] = 'less/main.less'; tasks[colors[color].name]['options']['modifyvars']['color'] = colors[color].color; alltaskarray.push('less:' + colors[color].name); } grunt.config('less',tasks); grunt.registertask( 'default', alltaskarray ); };

less/main.less:

@color: red; p{ color: @color; }

than run grunt:

running "less:8ab834f32" (less) task file dist/css/8ab834f32.css created: 24 b → 24 b

running "less:3cc734f31" (less) task file dist/css/3cc734f31.css created: 24 b → 24 b

done, without errors.

cat dist/css/3cc734f31.css:

p { color: #99981f; }

css gruntjs less

No comments:

Post a Comment