require-macro-variable-name.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * @author ItMaga
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const DEFAULT_OPTIONS = {
  8. defineProps: 'props',
  9. defineEmits: 'emit',
  10. defineSlots: 'slots',
  11. useSlots: 'slots',
  12. useAttrs: 'attrs'
  13. }
  14. module.exports = {
  15. meta: {
  16. type: 'suggestion',
  17. docs: {
  18. description: 'require a certain macro variable name',
  19. categories: undefined,
  20. url: 'https://eslint.vuejs.org/rules/require-macro-variable-name.html'
  21. },
  22. fixable: null,
  23. hasSuggestions: true,
  24. schema: [
  25. {
  26. type: 'object',
  27. properties: {
  28. defineProps: { type: 'string' },
  29. defineEmits: { type: 'string' },
  30. defineSlots: { type: 'string' },
  31. useSlots: { type: 'string' },
  32. useAttrs: { type: 'string' }
  33. },
  34. additionalProperties: false
  35. }
  36. ],
  37. messages: {
  38. requireName:
  39. 'The variable name of "{{macroName}}" must be "{{variableName}}".',
  40. changeName: 'Change the variable name to "{{variableName}}".'
  41. }
  42. },
  43. /** @param {RuleContext} context */
  44. create(context) {
  45. const options = Object.assign({}, DEFAULT_OPTIONS, context.options[0])
  46. const relevantMacros = new Set([
  47. ...Object.keys(DEFAULT_OPTIONS),
  48. 'withDefaults'
  49. ])
  50. return utils.defineScriptSetupVisitor(context, {
  51. VariableDeclarator(node) {
  52. if (
  53. node.init &&
  54. node.init.type === 'CallExpression' &&
  55. node.init.callee.type === 'Identifier' &&
  56. relevantMacros.has(node.init.callee.name)
  57. ) {
  58. const macroName =
  59. node.init.callee.name === 'withDefaults'
  60. ? 'defineProps'
  61. : node.init.callee.name
  62. if (
  63. node.id.type === 'Identifier' &&
  64. node.id.name !== options[macroName]
  65. ) {
  66. context.report({
  67. node: node.id,
  68. loc: node.id.loc,
  69. messageId: 'requireName',
  70. data: {
  71. macroName,
  72. variableName: options[macroName]
  73. },
  74. suggest: [
  75. {
  76. messageId: 'changeName',
  77. data: {
  78. variableName: options[macroName]
  79. },
  80. fix(fixer) {
  81. return fixer.replaceText(node.id, options[macroName])
  82. }
  83. }
  84. ]
  85. })
  86. }
  87. }
  88. }
  89. })
  90. }
  91. }