no-deprecated-destroyed-lifecycle.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @author Yosuke Ota
  3. * See LICENSE file in root directory for full license.
  4. */
  5. 'use strict'
  6. // ------------------------------------------------------------------------------
  7. // Requirements
  8. // ------------------------------------------------------------------------------
  9. const utils = require('../utils')
  10. // ------------------------------------------------------------------------------
  11. // Rule Definition
  12. // ------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. type: 'problem',
  16. docs: {
  17. description:
  18. 'disallow using deprecated `destroyed` and `beforeDestroy` lifecycle hooks (in Vue.js 3.0.0+)',
  19. categories: ['vue3-essential'],
  20. url: 'https://eslint.vuejs.org/rules/no-deprecated-destroyed-lifecycle.html'
  21. },
  22. fixable: 'code',
  23. schema: [],
  24. messages: {
  25. deprecatedDestroyed:
  26. 'The `destroyed` lifecycle hook is deprecated. Use `unmounted` instead.',
  27. deprecatedBeforeDestroy:
  28. 'The `beforeDestroy` lifecycle hook is deprecated. Use `beforeUnmount` instead.'
  29. }
  30. },
  31. /** @param {RuleContext} context */
  32. create(context) {
  33. return utils.executeOnVue(context, (obj) => {
  34. const destroyed = utils.findProperty(obj, 'destroyed')
  35. if (destroyed) {
  36. context.report({
  37. node: destroyed.key,
  38. messageId: 'deprecatedDestroyed',
  39. fix(fixer) {
  40. return fix(fixer, destroyed, 'unmounted')
  41. }
  42. })
  43. }
  44. const beforeDestroy = utils.findProperty(obj, 'beforeDestroy')
  45. if (beforeDestroy) {
  46. context.report({
  47. node: beforeDestroy.key,
  48. messageId: 'deprecatedBeforeDestroy',
  49. fix(fixer) {
  50. return fix(fixer, beforeDestroy, 'beforeUnmount')
  51. }
  52. })
  53. }
  54. /**
  55. * @param {RuleFixer} fixer
  56. * @param {Property} property
  57. * @param {string} newName
  58. */
  59. function fix(fixer, property, newName) {
  60. if (property.computed) {
  61. if (
  62. property.key.type === 'Literal' ||
  63. property.key.type === 'TemplateLiteral'
  64. ) {
  65. return fixer.replaceTextRange(
  66. [property.key.range[0] + 1, property.key.range[1] - 1],
  67. newName
  68. )
  69. }
  70. return null
  71. }
  72. if (property.shorthand) {
  73. return fixer.insertTextBefore(property.key, `${newName}:`)
  74. }
  75. return fixer.replaceText(property.key, newName)
  76. }
  77. })
  78. }
  79. }