require-func-head.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * @fileoverview enforce component's head property to be a function.
  3. * @author Xin Du <clark.duxin@gmail.com>
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. // ------------------------------------------------------------------------------
  8. // Rule Definition
  9. // ------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description: "enforce component's head property to be a function",
  14. category: 'recommended'
  15. },
  16. fixable: 'code',
  17. messages: {
  18. head: '`head` property in component must be a function.'
  19. }
  20. },
  21. create (context) {
  22. const sourceCode = context.getSourceCode()
  23. return utils.executeOnVueComponent(context, (obj) => {
  24. obj.properties
  25. .filter(p =>
  26. p.type === 'Property' &&
  27. p.key.type === 'Identifier' &&
  28. p.key.name === 'head' &&
  29. p.value.type !== 'FunctionExpression' &&
  30. p.value.type !== 'ArrowFunctionExpression' &&
  31. p.value.type !== 'Identifier' &&
  32. p.value.type !== 'CallExpression'
  33. )
  34. .forEach(p => {
  35. context.report({
  36. node: p,
  37. messageId: 'head',
  38. fix (fixer) {
  39. const tokens = utils.getFirstAndLastTokens(p.value, sourceCode)
  40. return [
  41. fixer.insertTextBefore(tokens.first, 'function() {\nreturn '),
  42. fixer.insertTextAfter(tokens.last, ';\n}')
  43. ]
  44. }
  45. })
  46. })
  47. })
  48. }
  49. }