index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import postcss from 'postcss';
  2. const OVERRIDABLE_RULES = ['keyframes', 'counter-style'];
  3. const SCOPE_RULES = ['media', 'supports'];
  4. function isOverridable (name) {
  5. return ~OVERRIDABLE_RULES.indexOf(postcss.vendor.unprefixed(name.toLowerCase()));
  6. }
  7. function isScope (name) {
  8. return ~SCOPE_RULES.indexOf(postcss.vendor.unprefixed(name.toLowerCase()));
  9. }
  10. function getScope (node) {
  11. let current = node.parent;
  12. const chain = [node.name.toLowerCase(), node.params];
  13. do {
  14. if (current.type === 'atrule' && isScope(current.name)) {
  15. chain.unshift(current.name + ' ' + current.params);
  16. }
  17. current = current.parent;
  18. } while (current);
  19. return chain.join('|');
  20. }
  21. export default postcss.plugin('postcss-discard-overridden', () => {
  22. return css => {
  23. const cache = {};
  24. const rules = [];
  25. css.walkAtRules(node => {
  26. if (isOverridable(node.name)) {
  27. const scope = getScope(node);
  28. cache[scope] = node;
  29. rules.push({
  30. node,
  31. scope,
  32. });
  33. }
  34. });
  35. rules.forEach(rule => {
  36. if (cache[rule.scope] !== rule.node) {
  37. rule.node.remove();
  38. }
  39. });
  40. };
  41. });