require-default-export.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @author ItMaga
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. module.exports = {
  8. meta: {
  9. type: 'problem',
  10. docs: {
  11. description: 'require components to be the default export',
  12. categories: undefined,
  13. url: 'https://eslint.vuejs.org/rules/require-default-export.html'
  14. },
  15. fixable: null,
  16. schema: [],
  17. messages: {
  18. missing: 'Missing default export.',
  19. mustBeDefaultExport: 'Component must be the default export.'
  20. }
  21. },
  22. /** @param {RuleContext} context */
  23. create(context) {
  24. const sourceCode = context.getSourceCode()
  25. const documentFragment = sourceCode.parserServices.getDocumentFragment?.()
  26. const hasScript =
  27. documentFragment &&
  28. documentFragment.children.some(
  29. (e) => utils.isVElement(e) && e.name === 'script'
  30. )
  31. if (utils.isScriptSetup(context) || !hasScript) {
  32. return {}
  33. }
  34. let hasDefaultExport = false
  35. let hasDefinedComponent = false
  36. return utils.compositingVisitors(
  37. utils.defineVueVisitor(context, {
  38. onVueObjectExit() {
  39. hasDefinedComponent = true
  40. }
  41. }),
  42. {
  43. 'Program > ExportDefaultDeclaration'() {
  44. hasDefaultExport = true
  45. },
  46. /**
  47. * @param {Program} node
  48. */
  49. 'Program:exit'(node) {
  50. if (!hasDefaultExport && node.body.length > 0) {
  51. context.report({
  52. loc: node.tokens[node.tokens.length - 1].loc,
  53. messageId: hasDefinedComponent ? 'mustBeDefaultExport' : 'missing'
  54. })
  55. }
  56. }
  57. }
  58. )
  59. }
  60. }