no-multi-comp.js 2.0 KB

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