Skip to content

Instantly share code, notes, and snippets.

@anteburazer
Last active April 27, 2017 08:19
Show Gist options
  • Save anteburazer/5a03094580694af1256d7b54ca5baa47 to your computer and use it in GitHub Desktop.
Save anteburazer/5a03094580694af1256d7b54ca5baa47 to your computer and use it in GitHub Desktop.
var fs = require('fs');
var mapFilePath = './classes-map.json';
var filesToReplace = [
{ path: './main.css', rename: './main-rename.css', type: 'css'},
{ path: './index.html', rename: './index-rename.html', type: 'html'},
{ path: './scripts.js', rename: './scripts-rename.js', type: 'js'}
];
/**
* Reads a file with mapped css classes and creates object literal
*
* @param mapFilePath: String
*/
function readMapFile(mapFilePath) {
var map = fs.readFileSync(mapFilePath).toString();
return JSON.parse(map);
}
/**
* Iterates over the files, replaces needed strings and creates new files with replaced characters
*
* @param map: Object
*/
function replace(map) {
for (var i = filesToReplace.length - 1; i >= 0; i--) {
var file = fs.readFileSync(filesToReplace[i].path).toString();
createFile(filesToReplace[i].rename, replacer(map, file, filesToReplace[i].type));
}
}
/**
* Replaces string in html, css and javascript files by corresponding regex
*
* @param map: Object
* @param data: String
* @param fileType: String
*/
function replacer(map, data, fileType) {
var regex;
for(className in map) {
switch(fileType) {
case 'css':
regex = new RegExp('(\\s)?(\\.)(' + className + ')(\\s|{|:|\n|,)', "gmi");
data = data.replace(regex, "$1$2" + map[className] + "$4");
break;
case 'html':
/*
* Rename class attributes
*
* TODO: Provjeriti regex
*/
regex = new RegExp('(class=")(' + className + ')(\\s|")', "gmi");
data = data.replace(regex, "$1" + map[className] + "$3");
/*
* Rename javascript selectors
*
* COVERED USE CASES:
* $(".fancyPopup")
* $('.fancyPopup')
* $(".fancyPopup div")
* $(".fancyPopup>div")
* $(".fancyPopup:first-child")
*
* TODO: Provjeriti regex
*/
regex = new RegExp('(\\s)?(\\.)(' + className + ')(\\s|"|:|>|\')', "gmi");
data = data.replace(regex, "$1$2" + map[className] + "$4");
break;
case 'js':
regex = new RegExp('(\\s)?(\\.)(' + className + ')(\\s|"|:|>|\')', "gmi");
data = data.replace(regex, "$1$2" + map[className] + "$4");
break;
default:
break;
}
}
return data;
}
/**
* Creates file with a given path and data
*
* @param filePath: String
* @param data: String
*/
function createFile(filePath, data) {
var content = fs.writeFileSync(filePath, data, 'utf8');
console.log("\x1b[32m", filePath + ' file successfully created');
console.log("\x1b[37m", '');
}
/**
* App bootstrap
*/
function init() {
replace(readMapFile(mapFilePath));
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment