valid-template-root.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2017 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. 'use strict'
  7. // ------------------------------------------------------------------------------
  8. // Requirements
  9. // ------------------------------------------------------------------------------
  10. const utils = require('../utils')
  11. // ------------------------------------------------------------------------------
  12. // Rule Definition
  13. // ------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. type: 'problem',
  17. docs: {
  18. description: 'enforce valid template root',
  19. categories: ['vue3-essential', 'essential'],
  20. url: 'https://eslint.vuejs.org/rules/valid-template-root.html'
  21. },
  22. fixable: null,
  23. schema: []
  24. },
  25. /** @param {RuleContext} context */
  26. create(context) {
  27. const sourceCode = context.getSourceCode()
  28. return {
  29. /** @param {Program} program */
  30. Program(program) {
  31. const element = program.templateBody
  32. if (element == null) {
  33. return
  34. }
  35. const hasSrc = utils.hasAttribute(element, 'src')
  36. const rootElements = []
  37. for (const child of element.children) {
  38. if (sourceCode.getText(child).trim() !== '') {
  39. rootElements.push(child)
  40. }
  41. }
  42. if (hasSrc && rootElements.length) {
  43. for (const element of rootElements) {
  44. context.report({
  45. node: element,
  46. loc: element.loc,
  47. message:
  48. "The template root with 'src' attribute is required to be empty."
  49. })
  50. }
  51. } else if (rootElements.length === 0 && !hasSrc) {
  52. context.report({
  53. node: element,
  54. loc: element.loc,
  55. message: 'The template requires child element.'
  56. })
  57. }
  58. }
  59. }
  60. }
  61. }