no-multi-comp.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * @fileoverview Prevent multiple component definition per file
  3. * @author Yannick Croissant
  4. */
  5. 'use strict';
  6. const Components = require('../util/Components');
  7. const docsUrl = require('../util/docsUrl');
  8. // ------------------------------------------------------------------------------
  9. // Rule Definition
  10. // ------------------------------------------------------------------------------
  11. module.exports = {
  12. meta: {
  13. docs: {
  14. description: 'Prevent multiple component definition per file',
  15. category: 'Stylistic Issues',
  16. recommended: false,
  17. url: docsUrl('no-multi-comp')
  18. },
  19. messages: {
  20. onlyOneComponent: 'Declare only one React component per file'
  21. },
  22. schema: [{
  23. type: 'object',
  24. properties: {
  25. ignoreStateless: {
  26. default: false,
  27. type: 'boolean'
  28. }
  29. },
  30. additionalProperties: false
  31. }]
  32. },
  33. create: Components.detect((context, components, utils) => {
  34. const configuration = context.options[0] || {};
  35. const ignoreStateless = configuration.ignoreStateless || false;
  36. /**
  37. * Checks if the component is ignored
  38. * @param {Object} component The component being checked.
  39. * @returns {Boolean} True if the component is ignored, false if not.
  40. */
  41. function isIgnored(component) {
  42. return (
  43. ignoreStateless && (
  44. /Function/.test(component.node.type)
  45. || utils.isPragmaComponentWrapper(component.node)
  46. )
  47. );
  48. }
  49. // --------------------------------------------------------------------------
  50. // Public
  51. // --------------------------------------------------------------------------
  52. return {
  53. 'Program:exit'() {
  54. if (components.length() <= 1) {
  55. return;
  56. }
  57. const list = components.list();
  58. Object.keys(list).filter((component) => !isIgnored(list[component])).forEach((component, i) => {
  59. if (i >= 1) {
  60. context.report({
  61. node: list[component].node,
  62. messageId: 'onlyOneComponent'
  63. });
  64. }
  65. });
  66. }
  67. };
  68. })
  69. };