Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Note: there would be comments in each portion of the file to guide the user. Need to add them still*/
- const crypto = require('crypto');
- const csstree = require('css-tree');
- const styleInjectionCode = (rawCss) => `
- var styleTag = document.createElement('style');
- var stylesTextNode = document.createTextNode('${rawCss}');
- styleTag.appendChild(stylesTextNode);
- var head = document.getElementsByTagName('head')[0];
- head.appendChild(styleTag);
- `;
- const localIdsExportCode = (localIds) => {
- const classExportsString = Object.keys(localIds).map((className) => {
- return `'${className}': '${localIds[className]}'`;
- }).join(',');
- return `
- module.exports = {
- ${classExportsString}
- };
- `;
- };
- function loader(filename, content){
- const localIds = {};
- const ast = csstree.parse(content);
- csstree.walk(ast, function(node){
- if(node.type === 'ClassSelector'){
- const hash = crypto.createHash('sha256');
- hash.update(`${filename}-${node.name}`);
- localIds[node.name] = hash.digest('base64');
- node.name = localIds[node.name];
- }
- });
- const transformedCss = csstree.generate(ast);
- const result = `
- ${styleInjectionCode(transformedCss)}
- ${localIdsExportCode(localIds)}
- `;
- return result;
- };
- module.exports = loader;
Add Comment
Please, Sign In to add comment