no-unused-styles.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * @fileoverview Detects unused styles
  3. * @author Tom Hastjarjanto
  4. */
  5. 'use strict';
  6. const Components = require('../util/Components');
  7. const styleSheet = require('../util/stylesheet');
  8. const { StyleSheets } = styleSheet;
  9. const { astHelpers } = styleSheet;
  10. const create = Components.detect((context, components) => {
  11. const styleSheets = new StyleSheets();
  12. const styleReferences = new Set();
  13. function reportUnusedStyles(unusedStyles) {
  14. Object.keys(unusedStyles).forEach((key) => {
  15. if ({}.hasOwnProperty.call(unusedStyles, key)) {
  16. const styles = unusedStyles[key];
  17. styles.forEach((node) => {
  18. const message = [
  19. 'Unused style detected: ',
  20. key,
  21. '.',
  22. node.key.name,
  23. ].join('');
  24. context.report(node, message);
  25. });
  26. }
  27. });
  28. }
  29. return {
  30. MemberExpression: function (node) {
  31. const styleRef = astHelpers.getPotentialStyleReferenceFromMemberExpression(node);
  32. if (styleRef) {
  33. styleReferences.add(styleRef);
  34. }
  35. },
  36. CallExpression: function (node) {
  37. if (astHelpers.isStyleSheetDeclaration(node, context.settings)) {
  38. const styleSheetName = astHelpers.getStyleSheetName(node);
  39. const styles = astHelpers.getStyleDeclarations(node);
  40. styleSheets.add(styleSheetName, styles);
  41. }
  42. },
  43. 'Program:exit': function () {
  44. const list = components.all();
  45. if (Object.keys(list).length > 0) {
  46. styleReferences.forEach((reference) => {
  47. styleSheets.markAsUsed(reference);
  48. });
  49. reportUnusedStyles(styleSheets.getUnusedReferences());
  50. }
  51. },
  52. };
  53. });
  54. module.exports = {
  55. meta: {
  56. schema: [],
  57. },
  58. create,
  59. };