提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.3 KiB

  1. 'use strict';
  2. const plugin = 'postcss-discard-empty';
  3. /**
  4. * @param {import('postcss').Root} css
  5. * @param {import('postcss').Result} result
  6. * @return {void}
  7. */
  8. function discardAndReport(css, result) {
  9. /**
  10. * @param {import('postcss').AnyNode} node
  11. * @return {void}
  12. */
  13. function discardEmpty(node) {
  14. const { type } = node;
  15. /** @type {(import('postcss').ChildNode | import('postcss').ChildProps)[] | undefined} */
  16. const sub = /** @type {any} */ (node).nodes;
  17. if (sub) {
  18. /** @type {import('postcss').Container} */ (node).each(discardEmpty);
  19. }
  20. if (
  21. (type === 'decl' && !node.value && !node.prop.startsWith('--')) ||
  22. (type === 'rule' && !node.selector) ||
  23. (sub && !sub.length) ||
  24. (type === 'atrule' &&
  25. ((!sub && !node.params) ||
  26. (!node.params &&
  27. !(/** @type {import('postcss').ChildNode[]}*/ (sub).length))))
  28. ) {
  29. node.remove();
  30. result.messages.push({
  31. type: 'removal',
  32. plugin,
  33. node,
  34. });
  35. }
  36. }
  37. css.each(discardEmpty);
  38. }
  39. /**
  40. * @type {import('postcss').PluginCreator<void>}
  41. * @return {import('postcss').Plugin}
  42. */
  43. function pluginCreator() {
  44. return {
  45. postcssPlugin: plugin,
  46. OnceExit(css, { result }) {
  47. discardAndReport(css, result);
  48. },
  49. };
  50. }
  51. pluginCreator.postcss = true;
  52. module.exports = pluginCreator;