Skip to content

Instantly share code, notes, and snippets.

@bauhouse
Created June 9, 2017 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bauhouse/a57c3b07365d91a6d0086c5d66cb5403 to your computer and use it in GitHub Desktop.
Save bauhouse/a57c3b07365d91a6d0086c5d66cb5403 to your computer and use it in GitHub Desktop.
Set CSS Properties based on JSON data from DatoCMS
// dato.config.js
var fs = require('fs');
module.exports = (dato, root, i18n) => {
// Modify SCSS properties in public/assets/css/colors.scss
// -------------------------------------------------------
// The file to modify
var file = 'public/assets/css/colors.scss';
// Find properties and assign new values
var properties = {
'$primary-color': dato.brand.primaryColor,
'$secondary-color': dato.brand.secondaryColor,
'$tertiary-color': dato.brand.tertiaryColor
};
// Write the changes to the file (omit properties to reset to default)
setCssProperties(file, properties);
};
function setCssProperties(file, properties) {
// The file to modify or set the default file
var file = file || 'public/assets/css/colors.scss';
// Find properties and assign new values or provide defaults
var properties = properties || {
'$primary-color': '#13c0d7',
'$secondary-color': '#8dc63f',
'$tertiary-color': '#f0bc00'
};
// Read file
fs.readFile(file, 'utf8', function (err,data) {
if (err) return console.log(err);
// Replace properties with regular expressions
var pattern = '';
var value = '';
var replace_str = '';
// Perform replacements on result
var result = data;
for (property in properties) {
// Build replacement strings for each property
pattern = '(\\' + property + ':)(.+?);';
value = properties[property];
replace_str = property + ': ' + value + ';'
// Replace the matching properties in the file
result = result.replace(RegExp(pattern, 'g'), replace_str);
}
// Write file
fs.writeFile(file, result, 'utf8', function (err) {
if (err) return console.log(err);
});
// Log change to console
console.log("\n* Written " + file);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment