restricted-component-names.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @author Wayne Zhang
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const { toRegExp } = require('../utils/regexp')
  8. const htmlElements = require('../utils/html-elements.json')
  9. const deprecatedHtmlElements = require('../utils/deprecated-html-elements.json')
  10. const svgElements = require('../utils/svg-elements.json')
  11. const vue2builtinComponents = require('../utils/vue2-builtin-components')
  12. const vue3builtinComponents = require('../utils/vue3-builtin-components')
  13. const reservedNames = new Set([
  14. ...htmlElements,
  15. ...deprecatedHtmlElements,
  16. ...svgElements,
  17. ...vue2builtinComponents,
  18. ...vue3builtinComponents
  19. ])
  20. module.exports = {
  21. meta: {
  22. type: 'problem',
  23. docs: {
  24. description: 'enforce using only specific component names',
  25. categories: undefined,
  26. url: 'https://eslint.vuejs.org/rules/restricted-component-names.html'
  27. },
  28. fixable: null,
  29. schema: [
  30. {
  31. type: 'object',
  32. additionalProperties: false,
  33. properties: {
  34. allow: {
  35. type: 'array',
  36. items: { type: 'string' },
  37. uniqueItems: true,
  38. additionalItems: false
  39. }
  40. }
  41. }
  42. ],
  43. messages: {
  44. invalidName: 'Component name "{{name}}" is not allowed.'
  45. }
  46. },
  47. /** @param {RuleContext} context */
  48. create(context) {
  49. const options = context.options[0] || {}
  50. /** @type {RegExp[]} */
  51. const allow = (options.allow || []).map(toRegExp)
  52. /** @param {string} name */
  53. function isAllowedTarget(name) {
  54. return reservedNames.has(name) || allow.some((re) => re.test(name))
  55. }
  56. return utils.defineTemplateBodyVisitor(context, {
  57. VElement(node) {
  58. const name = node.rawName
  59. if (isAllowedTarget(name)) {
  60. return
  61. }
  62. context.report({
  63. node,
  64. loc: node.loc,
  65. messageId: 'invalidName',
  66. data: {
  67. name
  68. }
  69. })
  70. }
  71. })
  72. }
  73. }