no-multi-comp.js 2.0 KB

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