Skip to content

Instantly share code, notes, and snippets.

@trevordixon
Created December 3, 2016 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trevordixon/839d0674531dafa98fb95ae51474245e to your computer and use it in GitHub Desktop.
Save trevordixon/839d0674531dafa98fb95ae51474245e to your computer and use it in GitHub Desktop.
const CSS = require('css');
function scopeCSS(css, scope) {
const ast = CSS.parse(css);
for (let rule of ast.stylesheet.rules) {
if (rule.type == 'rule') {
rule.selectors = rule.selectors.map(selector => `${scope} ${selector}`);
}
}
return CSS.stringify(ast);
}
const orig = 'div { color: black; } p, a, div > span { font-size: 20px; }';
const rewritten = scopeCSS(orig, '#foo');
const pre = document.createElement('pre');
pre.innerText =
`/* ORIGINAL */
${orig}
/* REWRITTEN */
${rewritten}`;
document.body.appendChild(pre);
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"css": "2.2.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment