Read LESS variables from the contents of a file and returning them as a javascript object.
$ npm install --save less-vars-to-js
I wrote this to use in our living style guide where we document our colour palette, typography, grid, components etc. This allows variables to be visualised in the style guide without having to read through the code (useful for non-technical team members).
import lessToJs from 'less-vars-to-js';
import fs from 'fs';
// Read the less file in as string
const paletteLess = fs.readFileSync('palette.less', 'utf8');
// Pass in file contents
const palette = lessToJs(paletteLess);
// Use the variables (example React component)
export default class Palette extends Component {
render() {
return (
<div>
{
Object.keys(palette)
.forEach(colour => (
<div style={{ backgroundColor: palette[colour] }}>
<p>{ colour }<p>
<p>{ palette[colour] }</p>
</div>
))
}
</div>
);
}
}