order-in-components.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * @fileoverview Keep order of properties in components
  3. * @author Michał Sajnóg
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const traverseNodes = require('vue-eslint-parser').AST.traverseNodes
  8. /**
  9. * @typedef {import('eslint-visitor-keys').VisitorKeys} VisitorKeys
  10. */
  11. const defaultOrder = [
  12. // Side Effects (triggers effects outside the component)
  13. 'el',
  14. // Global Awareness (requires knowledge beyond the component)
  15. 'name',
  16. 'key', // for Nuxt
  17. 'parent',
  18. // Component Type (changes the type of the component)
  19. 'functional',
  20. // Template Modifiers (changes the way templates are compiled)
  21. ['delimiters', 'comments'],
  22. // Template Dependencies (assets used in the template)
  23. ['components', 'directives', 'filters'],
  24. // Composition (merges properties into the options)
  25. 'extends',
  26. 'mixins',
  27. ['provide', 'inject'], // for Vue.js 2.2.0+
  28. // Page Options (component rendered as a router page)
  29. 'ROUTER_GUARDS', // for Vue Router
  30. 'layout', // for Nuxt
  31. 'middleware', // for Nuxt
  32. 'validate', // for Nuxt
  33. 'scrollToTop', // for Nuxt
  34. 'transition', // for Nuxt
  35. 'loading', // for Nuxt
  36. // Interface (the interface to the component)
  37. 'inheritAttrs',
  38. 'model',
  39. ['props', 'propsData'],
  40. 'emits', // for Vue.js 3.x
  41. // Note:
  42. // The `setup` option is included in the "Composition" category,
  43. // but the behavior of the `setup` option requires the definition of "Interface",
  44. // so we prefer to put the `setup` option after the "Interface".
  45. 'setup', // for Vue 3.x
  46. // Local State (local reactive properties)
  47. 'asyncData', // for Nuxt
  48. 'data',
  49. 'fetch', // for Nuxt
  50. 'head', // for Nuxt
  51. 'computed',
  52. // Events (callbacks triggered by reactive events)
  53. 'watch',
  54. 'watchQuery', // for Nuxt
  55. 'LIFECYCLE_HOOKS',
  56. // Non-Reactive Properties (instance properties independent of the reactivity system)
  57. 'methods',
  58. // Rendering (the declarative description of the component output)
  59. ['template', 'render'],
  60. 'renderError'
  61. ]
  62. /** @type { { [key: string]: string[] } } */
  63. const groups = {
  64. LIFECYCLE_HOOKS: [
  65. 'beforeCreate',
  66. 'created',
  67. 'beforeMount',
  68. 'mounted',
  69. 'beforeUpdate',
  70. 'updated',
  71. 'activated',
  72. 'deactivated',
  73. 'beforeUnmount', // for Vue.js 3.x
  74. 'unmounted', // for Vue.js 3.x
  75. 'beforeDestroy',
  76. 'destroyed',
  77. 'renderTracked', // for Vue.js 3.x
  78. 'renderTriggered', // for Vue.js 3.x
  79. 'errorCaptured' // for Vue.js 2.5.0+
  80. ],
  81. ROUTER_GUARDS: ['beforeRouteEnter', 'beforeRouteUpdate', 'beforeRouteLeave']
  82. }
  83. /**
  84. * @param {(string | string[])[]} order
  85. */
  86. function getOrderMap(order) {
  87. /** @type {Map<string, number>} */
  88. const orderMap = new Map()
  89. order.forEach((property, i) => {
  90. if (Array.isArray(property)) {
  91. property.forEach((p) => orderMap.set(p, i))
  92. } else {
  93. orderMap.set(property, i)
  94. }
  95. })
  96. return orderMap
  97. }
  98. /**
  99. * @param {Token} node
  100. */
  101. function isComma(node) {
  102. return node.type === 'Punctuator' && node.value === ','
  103. }
  104. const ARITHMETIC_OPERATORS = ['+', '-', '*', '/', '%', '**' /* es2016 */]
  105. const BITWISE_OPERATORS = ['&', '|', '^', '~', '<<', '>>', '>>>']
  106. const COMPARISON_OPERATORS = ['==', '!=', '===', '!==', '>', '>=', '<', '<=']
  107. const RELATIONAL_OPERATORS = ['in', 'instanceof']
  108. const ALL_BINARY_OPERATORS = [
  109. ...ARITHMETIC_OPERATORS,
  110. ...BITWISE_OPERATORS,
  111. ...COMPARISON_OPERATORS,
  112. ...RELATIONAL_OPERATORS
  113. ]
  114. const LOGICAL_OPERATORS = ['&&', '||', '??' /* es2020 */]
  115. /**
  116. * Result `true` if the node is sure that there are no side effects
  117. *
  118. * Currently known side effects types
  119. *
  120. * node.type === 'CallExpression'
  121. * node.type === 'NewExpression'
  122. * node.type === 'UpdateExpression'
  123. * node.type === 'AssignmentExpression'
  124. * node.type === 'TaggedTemplateExpression'
  125. * node.type === 'UnaryExpression' && node.operator === 'delete'
  126. *
  127. * @param {ASTNode} node target node
  128. * @param {VisitorKeys} visitorKeys sourceCode.visitorKey
  129. * @returns {boolean} no side effects
  130. */
  131. function isNotSideEffectsNode(node, visitorKeys) {
  132. let result = true
  133. /** @type {ASTNode | null} */
  134. let skipNode = null
  135. traverseNodes(node, {
  136. visitorKeys,
  137. /** @param {ASTNode} node */
  138. enterNode(node) {
  139. if (!result || skipNode) {
  140. return
  141. }
  142. if (
  143. // no side effects node
  144. node.type === 'FunctionExpression' ||
  145. node.type === 'Identifier' ||
  146. node.type === 'Literal' ||
  147. // es2015
  148. node.type === 'ArrowFunctionExpression' ||
  149. node.type === 'TemplateElement'
  150. ) {
  151. skipNode = node
  152. } else if (
  153. node.type !== 'Property' &&
  154. node.type !== 'ObjectExpression' &&
  155. node.type !== 'ArrayExpression' &&
  156. (node.type !== 'UnaryExpression' ||
  157. !['!', '~', '+', '-', 'typeof'].includes(node.operator)) &&
  158. (node.type !== 'BinaryExpression' ||
  159. !ALL_BINARY_OPERATORS.includes(node.operator)) &&
  160. (node.type !== 'LogicalExpression' ||
  161. !LOGICAL_OPERATORS.includes(node.operator)) &&
  162. node.type !== 'MemberExpression' &&
  163. node.type !== 'ConditionalExpression' &&
  164. // es2015
  165. node.type !== 'SpreadElement' &&
  166. node.type !== 'TemplateLiteral' &&
  167. // es2020
  168. node.type !== 'ChainExpression'
  169. ) {
  170. // Can not be sure that a node has no side effects
  171. result = false
  172. }
  173. },
  174. /** @param {ASTNode} node */
  175. leaveNode(node) {
  176. if (skipNode === node) {
  177. skipNode = null
  178. }
  179. }
  180. })
  181. return result
  182. }
  183. // ------------------------------------------------------------------------------
  184. // Rule Definition
  185. // ------------------------------------------------------------------------------
  186. module.exports = {
  187. meta: {
  188. type: 'suggestion',
  189. docs: {
  190. description: 'enforce order of properties in components',
  191. categories: ['vue3-recommended', 'recommended'],
  192. url: 'https://eslint.vuejs.org/rules/order-in-components.html'
  193. },
  194. fixable: 'code', // null or "code" or "whitespace"
  195. schema: [
  196. {
  197. type: 'object',
  198. properties: {
  199. order: {
  200. type: 'array'
  201. }
  202. },
  203. additionalProperties: false
  204. }
  205. ]
  206. },
  207. /** @param {RuleContext} context */
  208. create(context) {
  209. const options = context.options[0] || {}
  210. /** @type {(string|string[])[]} */
  211. const order = options.order || defaultOrder
  212. /** @type {(string|string[])[]} */
  213. const extendedOrder = order.map(
  214. (property) =>
  215. (typeof property === 'string' && groups[property]) || property
  216. )
  217. const orderMap = getOrderMap(extendedOrder)
  218. const sourceCode = context.getSourceCode()
  219. /**
  220. * @param {string} name
  221. */
  222. function getOrderPosition(name) {
  223. const num = orderMap.get(name)
  224. return num == null ? -1 : num
  225. }
  226. /**
  227. * @param {(Property | SpreadElement)[]} propertiesNodes
  228. */
  229. function checkOrder(propertiesNodes) {
  230. const properties = propertiesNodes
  231. .filter(utils.isProperty)
  232. .map((property) => {
  233. return {
  234. node: property,
  235. name:
  236. utils.getStaticPropertyName(property) ||
  237. (property.key.type === 'Identifier' && property.key.name) ||
  238. ''
  239. }
  240. })
  241. properties.forEach((property, i) => {
  242. const orderPos = getOrderPosition(property.name)
  243. if (orderPos < 0) {
  244. return
  245. }
  246. const propertiesAbove = properties.slice(0, i)
  247. const unorderedProperties = propertiesAbove
  248. .filter(
  249. (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
  250. )
  251. .sort((p1, p2) =>
  252. getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
  253. )
  254. const firstUnorderedProperty = unorderedProperties[0]
  255. if (firstUnorderedProperty) {
  256. const line = firstUnorderedProperty.node.loc.start.line
  257. context.report({
  258. node: property.node,
  259. message: `The "{{name}}" property should be above the "{{firstUnorderedPropertyName}}" property on line {{line}}.`,
  260. data: {
  261. name: property.name,
  262. firstUnorderedPropertyName: firstUnorderedProperty.name,
  263. line
  264. },
  265. *fix(fixer) {
  266. const propertyNode = property.node
  267. const firstUnorderedPropertyNode = firstUnorderedProperty.node
  268. const hasSideEffectsPossibility = propertiesNodes
  269. .slice(
  270. propertiesNodes.indexOf(firstUnorderedPropertyNode),
  271. propertiesNodes.indexOf(propertyNode) + 1
  272. )
  273. .some(
  274. (property) =>
  275. !isNotSideEffectsNode(property, sourceCode.visitorKeys)
  276. )
  277. if (hasSideEffectsPossibility) {
  278. return
  279. }
  280. const afterComma = sourceCode.getTokenAfter(propertyNode)
  281. const hasAfterComma = isComma(afterComma)
  282. const beforeComma = sourceCode.getTokenBefore(propertyNode)
  283. const codeStart = beforeComma.range[1] // to include comments
  284. const codeEnd = hasAfterComma
  285. ? afterComma.range[1]
  286. : propertyNode.range[1]
  287. const removeStart = hasAfterComma
  288. ? codeStart
  289. : beforeComma.range[0]
  290. yield fixer.removeRange([removeStart, codeEnd])
  291. const propertyCode =
  292. sourceCode.text.slice(codeStart, codeEnd) +
  293. (hasAfterComma ? '' : ',')
  294. const insertTarget = sourceCode.getTokenBefore(
  295. firstUnorderedPropertyNode
  296. )
  297. yield fixer.insertTextAfter(insertTarget, propertyCode)
  298. }
  299. })
  300. }
  301. })
  302. }
  303. return utils.executeOnVue(context, (obj) => {
  304. checkOrder(obj.properties)
  305. })
  306. }
  307. }