no-undef-components.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /**
  2. * @author Yosuke Ota
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const utils = require('../utils')
  10. const casing = require('../utils/casing')
  11. // ------------------------------------------------------------------------------
  12. // Rule helpers
  13. // ------------------------------------------------------------------------------
  14. /**
  15. * `casing.camelCase()` converts the beginning to lowercase,
  16. * but does not convert the case of the beginning character when converting with Vue3.
  17. * @see https://github.com/vuejs/core/blob/ae4b0783d78670b6e942ae2a4e3ec6efbbffa158/packages/shared/src/index.ts#L105
  18. * @param {string} str
  19. */
  20. function camelize(str) {
  21. return str.replace(/-(\w)/g, (_, c) => (c ? c.toUpperCase() : ''))
  22. }
  23. // ------------------------------------------------------------------------------
  24. // Rule Definition
  25. // ------------------------------------------------------------------------------
  26. module.exports = {
  27. meta: {
  28. type: 'suggestion',
  29. docs: {
  30. description: 'disallow use of undefined components in `<template>`',
  31. categories: undefined,
  32. url: 'https://eslint.vuejs.org/rules/no-undef-components.html'
  33. },
  34. fixable: null,
  35. schema: [
  36. {
  37. type: 'object',
  38. properties: {
  39. ignorePatterns: {
  40. type: 'array'
  41. }
  42. },
  43. additionalProperties: false
  44. }
  45. ],
  46. messages: {
  47. undef: "The '<{{name}}>' component has been used, but not defined."
  48. }
  49. },
  50. /** @param {RuleContext} context */
  51. create(context) {
  52. const options = context.options[0] || {}
  53. /** @type {string[]} */
  54. const ignorePatterns = options.ignorePatterns || []
  55. /**
  56. * Check whether the given element name is a verify target or not.
  57. *
  58. * @param {string} rawName The element name.
  59. * @returns {boolean}
  60. */
  61. function isVerifyTargetComponent(rawName) {
  62. const kebabCaseName = casing.kebabCase(rawName)
  63. if (
  64. utils.isHtmlWellKnownElementName(rawName) ||
  65. utils.isSvgWellKnownElementName(rawName) ||
  66. utils.isBuiltInComponentName(kebabCaseName)
  67. ) {
  68. return false
  69. }
  70. const pascalCaseName = casing.pascalCase(rawName)
  71. // Check ignored patterns
  72. if (
  73. ignorePatterns.some((pattern) => {
  74. const regExp = new RegExp(pattern)
  75. return (
  76. regExp.test(rawName) ||
  77. regExp.test(kebabCaseName) ||
  78. regExp.test(pascalCaseName)
  79. )
  80. })
  81. ) {
  82. return false
  83. }
  84. return true
  85. }
  86. /** @type { (rawName:string, reportNode: ASTNode) => void } */
  87. let verifyName
  88. /** @type {RuleListener} */
  89. let scriptVisitor = {}
  90. /** @type {TemplateListener} */
  91. const templateBodyVisitor = {
  92. VElement(node) {
  93. if (!utils.isHtmlElementNode(node) && !utils.isSvgElementNode(node)) {
  94. return
  95. }
  96. verifyName(node.rawName, node.startTag)
  97. },
  98. /** @param {VAttribute} node */
  99. "VAttribute[directive=false][key.name='is']"(node) {
  100. if (
  101. !node.value // `<component is />`
  102. )
  103. return
  104. const value = node.value.value.startsWith('vue:') // Usage on native elements 3.1+
  105. ? node.value.value.slice(4)
  106. : node.value.value
  107. verifyName(value, node)
  108. }
  109. }
  110. if (utils.isScriptSetup(context)) {
  111. // For <script setup>
  112. /** @type {Set<string>} */
  113. const scriptVariableNames = new Set()
  114. const globalScope = context.getSourceCode().scopeManager.globalScope
  115. if (globalScope) {
  116. for (const variable of globalScope.variables) {
  117. scriptVariableNames.add(variable.name)
  118. }
  119. const moduleScope = globalScope.childScopes.find(
  120. (scope) => scope.type === 'module'
  121. )
  122. for (const variable of (moduleScope && moduleScope.variables) || []) {
  123. scriptVariableNames.add(variable.name)
  124. }
  125. }
  126. /**
  127. * @see https://github.com/vuejs/core/blob/ae4b0783d78670b6e942ae2a4e3ec6efbbffa158/packages/compiler-core/src/transforms/transformElement.ts#L334
  128. * @param {string} name
  129. */
  130. const existsSetupReference = (name) => {
  131. if (scriptVariableNames.has(name)) {
  132. return true
  133. }
  134. const camelName = camelize(name)
  135. if (scriptVariableNames.has(camelName)) {
  136. return true
  137. }
  138. const pascalName = casing.capitalize(camelName)
  139. if (scriptVariableNames.has(pascalName)) {
  140. return true
  141. }
  142. return false
  143. }
  144. verifyName = (rawName, reportNode) => {
  145. if (!isVerifyTargetComponent(rawName)) {
  146. return
  147. }
  148. if (existsSetupReference(rawName)) {
  149. return
  150. }
  151. // Check namespace
  152. // https://github.com/vuejs/core/blob/ae4b0783d78670b6e942ae2a4e3ec6efbbffa158/packages/compiler-core/src/transforms/transformElement.ts#L305
  153. const dotIndex = rawName.indexOf('.')
  154. if (dotIndex > 0) {
  155. if (existsSetupReference(rawName.slice(0, dotIndex))) {
  156. return
  157. }
  158. }
  159. context.report({
  160. node: reportNode,
  161. messageId: 'undef',
  162. data: {
  163. name: rawName
  164. }
  165. })
  166. }
  167. } else {
  168. // For Options API
  169. /**
  170. * All registered components
  171. * @type {string[]}
  172. */
  173. const registeredComponentNames = []
  174. /**
  175. * All registered components, transformed to kebab-case
  176. * @type {string[]}
  177. */
  178. const registeredComponentKebabCaseNames = []
  179. /**
  180. * All registered components using kebab-case syntax
  181. * @type {string[]}
  182. */
  183. const componentsRegisteredAsKebabCase = []
  184. scriptVisitor = utils.executeOnVue(context, (obj) => {
  185. registeredComponentNames.push(
  186. ...utils.getRegisteredComponents(obj).map(({ name }) => name)
  187. )
  188. const nameProperty = utils.findProperty(obj, 'name')
  189. if (nameProperty && utils.isStringLiteral(nameProperty.value)) {
  190. const name = utils.getStringLiteralValue(nameProperty.value)
  191. if (name) {
  192. registeredComponentNames.push(name)
  193. }
  194. }
  195. registeredComponentKebabCaseNames.push(
  196. ...registeredComponentNames.map((name) => casing.kebabCase(name))
  197. )
  198. componentsRegisteredAsKebabCase.push(
  199. ...registeredComponentNames.filter(
  200. (name) => name === casing.kebabCase(name)
  201. )
  202. )
  203. })
  204. verifyName = (rawName, reportNode) => {
  205. if (!isVerifyTargetComponent(rawName)) {
  206. return
  207. }
  208. if (registeredComponentNames.includes(rawName)) {
  209. return
  210. }
  211. const kebabCaseName = casing.kebabCase(rawName)
  212. if (registeredComponentKebabCaseNames.includes(kebabCaseName)) {
  213. if (
  214. // Component registered as `foo-bar` cannot be used as `FooBar`
  215. !casing.isPascalCase(rawName)
  216. ) {
  217. return
  218. }
  219. }
  220. context.report({
  221. node: reportNode,
  222. messageId: 'undef',
  223. data: {
  224. name: rawName
  225. }
  226. })
  227. }
  228. /** @param {VDirective} node */
  229. templateBodyVisitor[
  230. "VAttribute[directive=true][key.name.name='bind'][key.argument.name='is'], VAttribute[directive=true][key.name.name='is']"
  231. ] = (node) => {
  232. if (
  233. !node.value ||
  234. node.value.type !== 'VExpressionContainer' ||
  235. !node.value.expression
  236. )
  237. return
  238. if (node.value.expression.type === 'Literal') {
  239. verifyName(`${node.value.expression.value}`, node)
  240. }
  241. }
  242. }
  243. return utils.defineTemplateBodyVisitor(
  244. context,
  245. templateBodyVisitor,
  246. scriptVisitor
  247. )
  248. }
  249. }