valid-template-root.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. const utils = require('../utils')
  8. module.exports = {
  9. meta: {
  10. type: 'problem',
  11. docs: {
  12. description: 'enforce valid template root',
  13. categories: ['vue3-essential', 'vue2-essential'],
  14. url: 'https://eslint.vuejs.org/rules/valid-template-root.html'
  15. },
  16. fixable: null,
  17. schema: [],
  18. messages: {
  19. emptySrc:
  20. "The template root with 'src' attribute is required to be empty.",
  21. noChild: 'The template requires child element.'
  22. }
  23. },
  24. /** @param {RuleContext} context */
  25. create(context) {
  26. const sourceCode = context.getSourceCode()
  27. return {
  28. /** @param {Program} program */
  29. Program(program) {
  30. const element = program.templateBody
  31. if (element == null) {
  32. return
  33. }
  34. const hasSrc = utils.hasAttribute(element, 'src')
  35. const rootElements = []
  36. for (const child of element.children) {
  37. if (sourceCode.getText(child).trim() !== '') {
  38. rootElements.push(child)
  39. }
  40. }
  41. if (hasSrc && rootElements.length > 0) {
  42. for (const element of rootElements) {
  43. context.report({
  44. node: element,
  45. loc: element.loc,
  46. messageId: 'emptySrc'
  47. })
  48. }
  49. } else if (rootElements.length === 0 && !hasSrc) {
  50. context.report({
  51. node: element,
  52. loc: element.loc,
  53. messageId: 'noChild'
  54. })
  55. }
  56. }
  57. }
  58. }
  59. }