Skip to content

Instantly share code, notes, and snippets.

@Danetag
Created January 18, 2018 11:14
Show Gist options
  • Save Danetag/d24746d6c0a0421faa4d663ac5ff8cdb to your computer and use it in GitHub Desktop.
Save Danetag/d24746d6c0a0421faa4d663ac5ff8cdb to your computer and use it in GitHub Desktop.
/*
* Based on https://medium.freecodecamp.org/reducing-css-bundle-size-70-by-cutting-the-class-names-and-using-scope-isolation-625440de600b
* Creates a shared dictionnary for client and server side classname rendering
*/
const incstr = require('incstr');
const fs = require('fs');
const jsonfile = require('jsonfile');
// creates dictionnary file if doesn't exists
if (!fs.existsSync(__dirname + '/scopeDictionnary.json')) fs.writeFileSync(__dirname + '/scopeDictionnary.json', '{}', { flag: 'wx' });
const scopeDict = require('./scopeDictionnary.json');
// Generates a unique ID
const createUniqueIdGenerator = () => {
const index = {};
const generateNextId = incstr.idGenerator({
// Removed "d" letter to avoid accidental "ad" construct.
// @see https://medium.com/@mbrevda/just-make-sure-ad-isnt-being-used-as-a-class-name-prefix-or-you-might-suffer-the-wrath-of-the-558d65502793
alphabet: 'abcefghijklmnopqrstuvwxyz0123456789'
});
return (name) => {
if (index[name]) {
return index[name];
}
let nextId;
do {
// Class name cannot start with a number.
nextId = generateNextId();
} while (/^[0-9]/.test(nextId));
index[name] = generateNextId();
return index[name];
};
};
const uniqueIdGenerator = createUniqueIdGenerator();
module.exports = function generateScopedName (localName, resourcePath, rebuild = false, localIdentName) {
// Build key based on component name
const aComponentName = resourcePath.split('/');
let componentName = '';
for (let i = aComponentName.indexOf('src') + 1; i < aComponentName.length; i++) {
componentName += aComponentName[i] + '_';
}
const key = componentName + localName;
// Return value if exists and in read mode
if (scopeDict[key] && !rebuild) return scopeDict[key];
let scopeDictionnary = jsonfile.readFileSync(__dirname + '/scopeDictionnary.json');
// writing the key/value
const generatedValue = uniqueIdGenerator(componentName) + '_' + uniqueIdGenerator(localName);
scopeDictionnary[key] = generatedValue;
jsonfile.writeFileSync(__dirname + "/scopeDictionnary.json", scopeDictionnary);
console.log("A key was created - ", key, ":", scopeDictionnary[key]);
return scopeDictionnary[key];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment