Guest User

Untitled

a guest
Jul 15th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. /* Note: there would be comments in each portion of the file to guide the user. Need to add them still*/
  2.  
  3. const crypto = require('crypto');
  4. const csstree = require('css-tree');
  5.  
  6. const styleInjectionCode = (rawCss) => `
  7. var styleTag = document.createElement('style');
  8. var stylesTextNode = document.createTextNode('${rawCss}');
  9. styleTag.appendChild(stylesTextNode);
  10. var head = document.getElementsByTagName('head')[0];
  11. head.appendChild(styleTag);
  12. `;
  13.  
  14. const localIdsExportCode = (localIds) => {
  15. const classExportsString = Object.keys(localIds).map((className) => {
  16. return `'${className}': '${localIds[className]}'`;
  17. }).join(',');
  18. return `
  19. module.exports = {
  20. ${classExportsString}
  21. };
  22. `;
  23. };
  24.  
  25. function loader(filename, content){
  26.  
  27. const localIds = {};
  28.  
  29. const ast = csstree.parse(content);
  30.  
  31. csstree.walk(ast, function(node){
  32. if(node.type === 'ClassSelector'){
  33. const hash = crypto.createHash('sha256');
  34. hash.update(`${filename}-${node.name}`);
  35. localIds[node.name] = hash.digest('base64');
  36. node.name = localIds[node.name];
  37. }
  38. });
  39.  
  40. const transformedCss = csstree.generate(ast);
  41.  
  42. const result = `
  43. ${styleInjectionCode(transformedCss)}
  44. ${localIdsExportCode(localIds)}
  45. `;
  46. return result;
  47. };
  48.  
  49. module.exports = loader;
Add Comment
Please, Sign In to add comment