Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
test cssom, demonstrate a minimum css module implementation
const css = require('css');
const crypto = require('crypto');
const assert = require('assert');
var style = `.foo {
color: green;
}
.bar {
color: red;
}
`;
var hash = crypto.createHash('md5').update(style).digest("hex").substr(0, 8);
var obj = css.parse(style);
// console.log(JSON.stringify(obj, null, 3));
obj.stylesheet.rules.forEach((rule) => {
rule.selectors = rule.selectors.map((selector) => {
return `${selector}[${hash}]`;
});
});
var transformed = `.foo[bf17e64c] {
color: green;
}
.bar[bf17e64c] {
color: red;
}`
console.log('#'.repeat(20), '\n', css.stringify(obj));
assert.equal(css.stringify(obj), transformed);
Owner

dongyuwei commented Jul 10, 2017

cssom structure

{
   "type": "stylesheet",
   "stylesheet": {
      "rules": [
         {
            "type": "rule",
            "selectors": [
               ".foo"
            ],
            "declarations": [
               {
                  "type": "declaration",
                  "property": "color",
                  "value": "green",
                  "position": {
                     "start": {
                        "line": 2,
                        "column": 17
                     },
                     "end": {
                        "line": 2,
                        "column": 29
                     }
                  }
               }
            ],
            "position": {
               "start": {
                  "line": 1,
                  "column": 1
               },
               "end": {
                  "line": 3,
                  "column": 15
               }
            }
         },
         {
            "type": "rule",
            "selectors": [
               ".bar"
            ],
            "declarations": [
               {
                  "type": "declaration",
                  "property": "color",
                  "value": "red",
                  "position": {
                     "start": {
                        "line": 5,
                        "column": 17
                     },
                     "end": {
                        "line": 5,
                        "column": 27
                     }
                  }
               }
            ],
            "position": {
               "start": {
                  "line": 4,
                  "column": 14
               },
               "end": {
                  "line": 6,
                  "column": 15
               }
            }
         }
      ],
      "parsingErrors": []
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment