order-in-components.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. for (const [i, property] of order.entries()) {
  90. if (Array.isArray(property)) {
  91. for (const p of property) {
  92. orderMap.set(p, i)
  93. }
  94. } else {
  95. orderMap.set(property, i)
  96. }
  97. }
  98. return orderMap
  99. }
  100. /**
  101. * @param {Token} node
  102. */
  103. function isComma(node) {
  104. return node.type === 'Punctuator' && node.value === ','
  105. }
  106. const ARITHMETIC_OPERATORS = ['+', '-', '*', '/', '%', '**' /* es2016 */]
  107. const BITWISE_OPERATORS = ['&', '|', '^', '~', '<<', '>>', '>>>']
  108. const COMPARISON_OPERATORS = ['==', '!=', '===', '!==', '>', '>=', '<', '<=']
  109. const RELATIONAL_OPERATORS = ['in', 'instanceof']
  110. const ALL_BINARY_OPERATORS = new Set([
  111. ...ARITHMETIC_OPERATORS,
  112. ...BITWISE_OPERATORS,
  113. ...COMPARISON_OPERATORS,
  114. ...RELATIONAL_OPERATORS
  115. ])
  116. const LOGICAL_OPERATORS = new Set(['&&', '||', '??' /* es2020 */])
  117. /**
  118. * Result `true` if the node is sure that there are no side effects
  119. *
  120. * Currently known side effects types
  121. *
  122. * node.type === 'CallExpression'
  123. * node.type === 'NewExpression'
  124. * node.type === 'UpdateExpression'
  125. * node.type === 'AssignmentExpression'
  126. * node.type === 'TaggedTemplateExpression'
  127. * node.type === 'UnaryExpression' && node.operator === 'delete'
  128. *
  129. * @param {ASTNode} node target node
  130. * @param {VisitorKeys} visitorKeys sourceCode.visitorKey
  131. * @returns {boolean} no side effects
  132. */
  133. function isNotSideEffectsNode(node, visitorKeys) {
  134. let result = true
  135. /** @type {ASTNode | null} */
  136. let skipNode = null
  137. traverseNodes(node, {
  138. visitorKeys,
  139. /** @param {ASTNode} node */
  140. enterNode(node) {
  141. if (!result || skipNode) {
  142. return
  143. }
  144. if (
  145. // no side effects node
  146. node.type === 'FunctionExpression' ||
  147. node.type === 'Identifier' ||
  148. node.type === 'Literal' ||
  149. // es2015
  150. node.type === 'ArrowFunctionExpression' ||
  151. node.type === 'TemplateElement' ||
  152. // typescript
  153. node.type === 'TSAsExpression'
  154. ) {
  155. skipNode = node
  156. } else if (
  157. node.type !== 'Property' &&
  158. node.type !== 'ObjectExpression' &&
  159. node.type !== 'ArrayExpression' &&
  160. (node.type !== 'UnaryExpression' ||
  161. !['!', '~', '+', '-', 'typeof'].includes(node.operator)) &&
  162. (node.type !== 'BinaryExpression' ||
  163. !ALL_BINARY_OPERATORS.has(node.operator)) &&
  164. (node.type !== 'LogicalExpression' ||
  165. !LOGICAL_OPERATORS.has(node.operator)) &&
  166. node.type !== 'MemberExpression' &&
  167. node.type !== 'ConditionalExpression' &&
  168. // es2015
  169. node.type !== 'SpreadElement' &&
  170. node.type !== 'TemplateLiteral' &&
  171. // es2020
  172. node.type !== 'ChainExpression'
  173. ) {
  174. // Can not be sure that a node has no side effects
  175. result = false
  176. }
  177. },
  178. /** @param {ASTNode} node */
  179. leaveNode(node) {
  180. if (skipNode === node) {
  181. skipNode = null
  182. }
  183. }
  184. })
  185. return result
  186. }
  187. module.exports = {
  188. meta: {
  189. type: 'suggestion',
  190. docs: {
  191. description: 'enforce order of properties in components',
  192. categories: ['vue3-recommended', 'recommended'],
  193. url: 'https://eslint.vuejs.org/rules/order-in-components.html'
  194. },
  195. fixable: 'code', // null or "code" or "whitespace"
  196. schema: [
  197. {
  198. type: 'object',
  199. properties: {
  200. order: {
  201. type: 'array'
  202. }
  203. },
  204. additionalProperties: false
  205. }
  206. ]
  207. },
  208. /** @param {RuleContext} context */
  209. create(context) {
  210. const options = context.options[0] || {}
  211. /** @type {(string|string[])[]} */
  212. const order = options.order || defaultOrder
  213. /** @type {(string|string[])[]} */
  214. const extendedOrder = order.map(
  215. (property) =>
  216. (typeof property === 'string' && groups[property]) || property
  217. )
  218. const orderMap = getOrderMap(extendedOrder)
  219. const sourceCode = context.getSourceCode()
  220. /**
  221. * @param {string} name
  222. */
  223. function getOrderPosition(name) {
  224. const num = orderMap.get(name)
  225. return num == null ? -1 : num
  226. }
  227. /**
  228. * @param {(Property | SpreadElement)[]} propertiesNodes
  229. */
  230. function checkOrder(propertiesNodes) {
  231. const properties = propertiesNodes
  232. .filter(utils.isProperty)
  233. .map((property) => ({
  234. node: property,
  235. name:
  236. utils.getStaticPropertyName(property) ||
  237. (property.key.type === 'Identifier' && property.key.name) ||
  238. ''
  239. }))
  240. for (const [i, property] of properties.entries()) {
  241. const orderPos = getOrderPosition(property.name)
  242. if (orderPos < 0) {
  243. continue
  244. }
  245. const propertiesAbove = properties.slice(0, i)
  246. const unorderedProperties = propertiesAbove
  247. .filter(
  248. (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
  249. )
  250. .sort((p1, p2) =>
  251. getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
  252. )
  253. const firstUnorderedProperty = unorderedProperties[0]
  254. if (firstUnorderedProperty) {
  255. const line = firstUnorderedProperty.node.loc.start.line
  256. context.report({
  257. node: property.node,
  258. message: `The "{{name}}" property should be above the "{{firstUnorderedPropertyName}}" property on line {{line}}.`,
  259. data: {
  260. name: property.name,
  261. firstUnorderedPropertyName: firstUnorderedProperty.name,
  262. line
  263. },
  264. *fix(fixer) {
  265. const propertyNode = property.node
  266. const firstUnorderedPropertyNode = firstUnorderedProperty.node
  267. const hasSideEffectsPossibility = propertiesNodes
  268. .slice(
  269. propertiesNodes.indexOf(firstUnorderedPropertyNode),
  270. propertiesNodes.indexOf(propertyNode) + 1
  271. )
  272. .some(
  273. (property) =>
  274. !isNotSideEffectsNode(property, sourceCode.visitorKeys)
  275. )
  276. if (hasSideEffectsPossibility) {
  277. return
  278. }
  279. const afterComma = sourceCode.getTokenAfter(propertyNode)
  280. const hasAfterComma = isComma(afterComma)
  281. const beforeComma = sourceCode.getTokenBefore(propertyNode)
  282. const codeStart = beforeComma.range[1] // to include comments
  283. const codeEnd = hasAfterComma
  284. ? afterComma.range[1]
  285. : propertyNode.range[1]
  286. const removeStart = hasAfterComma
  287. ? codeStart
  288. : beforeComma.range[0]
  289. yield fixer.removeRange([removeStart, codeEnd])
  290. const propertyCode =
  291. sourceCode.text.slice(codeStart, codeEnd) +
  292. (hasAfterComma ? '' : ',')
  293. const insertTarget = sourceCode.getTokenBefore(
  294. firstUnorderedPropertyNode
  295. )
  296. yield fixer.insertTextAfter(insertTarget, propertyCode)
  297. }
  298. })
  299. }
  300. }
  301. }
  302. return utils.executeOnVue(context, (obj) => {
  303. checkOrder(obj.properties)
  304. })
  305. }
  306. }