Skip to content

Instantly share code, notes, and snippets.

@lac5
Created March 18, 2020 19:59
Show Gist options
  • Save lac5/a2bdf29f972e521a51875e5dedccfa30 to your computer and use it in GitHub Desktop.
Save lac5/a2bdf29f972e521a51875e5dedccfa30 to your computer and use it in GitHub Desktop.
import { getOptions } from 'loader-utils';
import CSS from 'css';
import XRegExp from 'xregexp';
export default function cssPrefixLoader(content) {
const { prefix, ...options } = getOptions(this);
let ast = CSS.parse(content);
addPrefixes(prefix, ast.stylesheet.rules);
return CSS.stringify(ast, options);
}
const selectorRx = XRegExp('(?<=[.#])([a-zA-Z0-9_-]+)', 'g');
function addPrefixes(prefix, rules) {
for (let rule of rules) {
if (rule.selectors) {
rule.selectors = rule.selectors.map(selector =>
selector.replace(selectorRx, prefix + '$1')
);
}
if (rule.rules) {
addPrefixes(prefix, rule.rules);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment