no-property-shorthands.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const { isOpeningBracketToken, isClosingBracketToken } = require("eslint-utils")
  7. module.exports = {
  8. meta: {
  9. docs: {
  10. description: "disallow property shorthands.",
  11. category: "ES2015",
  12. recommended: false,
  13. url:
  14. "http://mysticatea.github.io/eslint-plugin-es/rules/no-property-shorthands.html",
  15. },
  16. fixable: "code",
  17. messages: {
  18. forbidden: "ES2015 property shorthands are forbidden.",
  19. },
  20. schema: [],
  21. type: "problem",
  22. },
  23. create(context) {
  24. const sourceCode = context.getSourceCode()
  25. /**
  26. * Fixes a FunctionExpression node by making it into a longform property.
  27. * @param {SourceCodeFixer} fixer The fixer object
  28. * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value
  29. * @returns {object} A fix for this node
  30. */
  31. function makeFunctionLongform(fixer, node) {
  32. const firstKeyToken = node.computed
  33. ? sourceCode.getTokenBefore(node.key, isOpeningBracketToken)
  34. : sourceCode.getFirstToken(node.key)
  35. const lastKeyToken = node.computed
  36. ? sourceCode.getTokenAfter(node.key, isClosingBracketToken)
  37. : sourceCode.getLastToken(node.key)
  38. const keyText = sourceCode.text.slice(
  39. firstKeyToken.range[0],
  40. lastKeyToken.range[1]
  41. )
  42. let functionHeader = "function"
  43. if (node.value.async) {
  44. functionHeader = `async ${functionHeader}`
  45. }
  46. if (node.value.generator) {
  47. functionHeader = `${functionHeader}*`
  48. }
  49. return fixer.replaceTextRange(
  50. [node.range[0], lastKeyToken.range[1]],
  51. `${keyText}: ${functionHeader}`
  52. )
  53. }
  54. return {
  55. "ObjectExpression > :matches(Property[method=true], Property[shorthand=true])"(
  56. node
  57. ) {
  58. context.report({
  59. node,
  60. messageId: "forbidden",
  61. fix: node.method
  62. ? fixer => makeFunctionLongform(fixer, node)
  63. : fixer =>
  64. fixer.insertTextAfter(
  65. node.key,
  66. `: ${node.key.name}`
  67. ),
  68. })
  69. },
  70. }
  71. },
  72. }