no-deprecated-data-object-declaration.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @fileoverview disallow using deprecated object declaration on data
  3. * @author yoyo930021
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. /** @param {Token} token */
  8. function isOpenParen(token) {
  9. return token.type === 'Punctuator' && token.value === '('
  10. }
  11. /** @param {Token} token */
  12. function isCloseParen(token) {
  13. return token.type === 'Punctuator' && token.value === ')'
  14. }
  15. /**
  16. * @param {Expression} node
  17. * @param {SourceCode} sourceCode
  18. */
  19. function getFirstAndLastTokens(node, sourceCode) {
  20. let first = sourceCode.getFirstToken(node)
  21. let last = sourceCode.getLastToken(node)
  22. // If the value enclosed by parentheses, update the 'first' and 'last' by the parentheses.
  23. while (true) {
  24. const prev = sourceCode.getTokenBefore(first)
  25. const next = sourceCode.getTokenAfter(last)
  26. if (isOpenParen(prev) && isCloseParen(next)) {
  27. first = prev
  28. last = next
  29. } else {
  30. return { first, last }
  31. }
  32. }
  33. }
  34. module.exports = {
  35. meta: {
  36. type: 'problem',
  37. docs: {
  38. description:
  39. 'disallow using deprecated object declaration on data (in Vue.js 3.0.0+)',
  40. categories: ['vue3-essential'],
  41. url: 'https://eslint.vuejs.org/rules/no-deprecated-data-object-declaration.html'
  42. },
  43. fixable: 'code',
  44. schema: [],
  45. messages: {
  46. objectDeclarationIsDeprecated:
  47. "Object declaration on 'data' property is deprecated. Using function declaration instead."
  48. }
  49. },
  50. /** @param {RuleContext} context */
  51. create(context) {
  52. const sourceCode = context.getSourceCode()
  53. return utils.executeOnVue(context, (obj) => {
  54. const invalidData = utils.findProperty(
  55. obj,
  56. 'data',
  57. (p) =>
  58. p.value.type !== 'FunctionExpression' &&
  59. p.value.type !== 'ArrowFunctionExpression' &&
  60. p.value.type !== 'Identifier'
  61. )
  62. if (invalidData) {
  63. context.report({
  64. node: invalidData,
  65. messageId: 'objectDeclarationIsDeprecated',
  66. fix(fixer) {
  67. const tokens = getFirstAndLastTokens(invalidData.value, sourceCode)
  68. return [
  69. fixer.insertTextBefore(tokens.first, 'function() {\nreturn '),
  70. fixer.insertTextAfter(tokens.last, ';\n}')
  71. ]
  72. }
  73. })
  74. }
  75. })
  76. }
  77. }