I have a LESS file with color definitions:
@RED: #CE1512;
@BLUE: #3E83A0;
// ...
I now have need of using these color definitions in my JavaScript as well.
How best to share code like this between LESS and JavaScript?
I have a LESS file with color definitions:
@RED: #CE1512;
@BLUE: #3E83A0;
// ...
I now have need of using these color definitions in my JavaScript as well.
How best to share code like this between LESS and JavaScript?
I ended up coming up with my own solution, though I think I will try to avoid using it all-together (per the reasons listed by alttag).
Vohuman's answer provides another solution, but I don't really like the idea of embedding js directly in my LESS file, so would prefer an approach like below.
I created the following node.js
module which will read a json file and output a less file.
var fs = require('fs');
var EOL = require('os').EOL;
module.exports = function (jsonFile, outputFileName) {
var json = require(jsonFile);
var lessFileContent = "";
for (color in json) {
var lessColorDefinition = '@' + color + ': ' + json[color] + ';';
lessFileContent += lessColorDefinition + EOL;
};
fs.writeFile(outputFileName, lessFileContent);
};
Example json file:
{
"RED": "#CE1512",
"BLUE": "#3E83A0"
}
Example usage in Gulp task:
var j2l = require('./baseStyles/jsonToLess');
gulp.task('build-base-less', function() {
j2l('./colors.json', 'colors.less');
});
The short answer to one of your questions is no, no it is not a good idea to use it in your javascript. In general, it is best to keep color and other visual information in CSS, and behavior information in javascript.
Exceptions should be exceedingly rare.
Is this even a good idea?
It depends on the application needs and how it's structured. If you have so many variables and your JavaScript heavily needs them then it makes sense. Otherwise having duplicates in both environments can be considered too.
Which should be the pre-compiled source? (js or less)
JavaScript as LESS compiler also understands JavaScript; however, JSON, in this case is the best option.
Does something like this already exist?
You could create a json file and import it in your LESS file. In JavaScript the file can be easily loaded by using Ajax.