match-component-import-name.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * @author Doug Wade <douglas.b.wade@gmail.com>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const casing = require('../utils/casing')
  8. module.exports = {
  9. meta: {
  10. type: 'problem',
  11. schema: [],
  12. docs: {
  13. description:
  14. 'require the registered component name to match the imported component name',
  15. categories: undefined,
  16. url: 'https://eslint.vuejs.org/rules/match-component-import-name.html'
  17. },
  18. fixable: null,
  19. messages: {
  20. unexpected:
  21. 'Component alias {{importedName}} should be one of: {{expectedName}}.'
  22. }
  23. },
  24. /**
  25. * @param {RuleContext} context
  26. * @returns {RuleListener}
  27. */
  28. create(context) {
  29. /**
  30. * @param {Identifier} identifier
  31. * @return {Array<String>}
  32. */
  33. function getExpectedNames(identifier) {
  34. return [
  35. casing.pascalCase(identifier.name),
  36. casing.kebabCase(identifier.name)
  37. ]
  38. }
  39. return utils.executeOnVueComponent(context, (obj) => {
  40. const components = utils.findProperty(obj, 'components')
  41. if (
  42. !components ||
  43. !components.value ||
  44. components.value.type !== 'ObjectExpression'
  45. ) {
  46. return
  47. }
  48. components.value.properties.forEach(
  49. /** @param {Property | SpreadElement} property */
  50. (property) => {
  51. if (
  52. property.type === 'SpreadElement' ||
  53. property.value.type !== 'Identifier' ||
  54. property.computed === true
  55. ) {
  56. return
  57. }
  58. const importedName = utils.getStaticPropertyName(property) || ''
  59. const expectedNames = getExpectedNames(property.value)
  60. if (!expectedNames.includes(importedName)) {
  61. context.report({
  62. node: property,
  63. messageId: 'unexpected',
  64. data: {
  65. importedName,
  66. expectedName: expectedNames.join(', ')
  67. }
  68. })
  69. }
  70. }
  71. )
  72. })
  73. }
  74. }