max-props.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * @author kevsommer Kevin Sommer
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. module.exports = {
  8. meta: {
  9. type: 'problem',
  10. docs: {
  11. description: 'enforce maximum number of props in Vue component',
  12. categories: undefined,
  13. url: 'https://eslint.vuejs.org/rules/max-props.html'
  14. },
  15. fixable: null,
  16. schema: [
  17. {
  18. type: 'object',
  19. properties: {
  20. maxProps: {
  21. type: 'integer',
  22. minimum: 1
  23. }
  24. },
  25. additionalProperties: false,
  26. minProperties: 1
  27. }
  28. ],
  29. messages: {
  30. tooManyProps:
  31. 'Component has too many props ({{propCount}}). Maximum allowed is {{limit}}.'
  32. }
  33. },
  34. /** @param {RuleContext} context */
  35. create(context) {
  36. /** @type {Record<string, number>} */
  37. const option = context.options[0] || {}
  38. /**
  39. * @param {import('../utils').ComponentProp[]} props
  40. * @param {CallExpression | Property} node
  41. */
  42. function checkMaxNumberOfProps(props, node) {
  43. const uniqueProps = new Set(props.map((prop) => prop.propName))
  44. const propCount = uniqueProps.size
  45. if (propCount > option.maxProps && props[0].node) {
  46. context.report({
  47. node,
  48. messageId: 'tooManyProps',
  49. data: {
  50. propCount,
  51. limit: option.maxProps
  52. }
  53. })
  54. }
  55. }
  56. return utils.compositingVisitors(
  57. utils.executeOnVue(context, (node) => {
  58. const propsNode = node.properties.find(
  59. /** @returns {p is Property} */
  60. (p) =>
  61. p.type === 'Property' && utils.getStaticPropertyName(p) === 'props'
  62. )
  63. if (!propsNode) return
  64. checkMaxNumberOfProps(
  65. utils.getComponentPropsFromOptions(node),
  66. propsNode
  67. )
  68. }),
  69. utils.defineScriptSetupVisitor(context, {
  70. onDefinePropsEnter(node, props) {
  71. checkMaxNumberOfProps(props, node)
  72. }
  73. })
  74. )
  75. }
  76. }