order-in-components.js 9.7 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. 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. enterNode(node) {
  138. if (!result || skipNode) {
  139. return
  140. }
  141. if (
  142. // no side effects node
  143. node.type === 'FunctionExpression' ||
  144. node.type === 'Identifier' ||
  145. node.type === 'Literal' ||
  146. // es2015
  147. node.type === 'ArrowFunctionExpression' ||
  148. node.type === 'TemplateElement'
  149. ) {
  150. skipNode = node
  151. } else if (
  152. node.type !== 'Property' &&
  153. node.type !== 'ObjectExpression' &&
  154. node.type !== 'ArrayExpression' &&
  155. (node.type !== 'UnaryExpression' ||
  156. !['!', '~', '+', '-', 'typeof'].includes(node.operator)) &&
  157. (node.type !== 'BinaryExpression' ||
  158. !ALL_BINARY_OPERATORS.includes(node.operator)) &&
  159. (node.type !== 'LogicalExpression' ||
  160. !LOGICAL_OPERATORS.includes(node.operator)) &&
  161. node.type !== 'MemberExpression' &&
  162. node.type !== 'ConditionalExpression' &&
  163. // es2015
  164. node.type !== 'SpreadElement' &&
  165. node.type !== 'TemplateLiteral' &&
  166. // es2020
  167. node.type !== 'ChainExpression'
  168. ) {
  169. // Can not be sure that a node has no side effects
  170. result = false
  171. }
  172. },
  173. leaveNode(node) {
  174. if (skipNode === node) {
  175. skipNode = null
  176. }
  177. }
  178. })
  179. return result
  180. }
  181. // ------------------------------------------------------------------------------
  182. // Rule Definition
  183. // ------------------------------------------------------------------------------
  184. module.exports = {
  185. meta: {
  186. type: 'suggestion',
  187. docs: {
  188. description: 'enforce order of properties in components',
  189. categories: ['vue3-recommended', 'recommended'],
  190. url: 'https://eslint.vuejs.org/rules/order-in-components.html'
  191. },
  192. fixable: 'code', // null or "code" or "whitespace"
  193. schema: [
  194. {
  195. type: 'object',
  196. properties: {
  197. order: {
  198. type: 'array'
  199. }
  200. },
  201. additionalProperties: false
  202. }
  203. ]
  204. },
  205. /** @param {RuleContext} context */
  206. create(context) {
  207. const options = context.options[0] || {}
  208. /** @type {(string|string[])[]} */
  209. const order = options.order || defaultOrder
  210. /** @type {(string|string[])[]} */
  211. const extendedOrder = order.map(
  212. (property) =>
  213. (typeof property === 'string' && groups[property]) || property
  214. )
  215. const orderMap = getOrderMap(extendedOrder)
  216. const sourceCode = context.getSourceCode()
  217. /**
  218. * @param {string} name
  219. */
  220. function getOrderPosition(name) {
  221. const num = orderMap.get(name)
  222. return num == null ? -1 : num
  223. }
  224. /**
  225. * @param {(Property | SpreadElement)[]} propertiesNodes
  226. */
  227. function checkOrder(propertiesNodes) {
  228. const properties = propertiesNodes
  229. .filter(utils.isProperty)
  230. .map((property) => {
  231. return {
  232. node: property,
  233. name:
  234. utils.getStaticPropertyName(property) ||
  235. (property.key.type === 'Identifier' && property.key.name) ||
  236. ''
  237. }
  238. })
  239. properties.forEach((property, i) => {
  240. const orderPos = getOrderPosition(property.name)
  241. if (orderPos < 0) {
  242. return
  243. }
  244. const propertiesAbove = properties.slice(0, i)
  245. const unorderedProperties = propertiesAbove
  246. .filter(
  247. (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
  248. )
  249. .sort((p1, p2) =>
  250. getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
  251. )
  252. const firstUnorderedProperty = unorderedProperties[0]
  253. if (firstUnorderedProperty) {
  254. const line = firstUnorderedProperty.node.loc.start.line
  255. context.report({
  256. node: property.node,
  257. message: `The "{{name}}" property should be above the "{{firstUnorderedPropertyName}}" property on line {{line}}.`,
  258. data: {
  259. name: property.name,
  260. firstUnorderedPropertyName: firstUnorderedProperty.name,
  261. line
  262. },
  263. *fix(fixer) {
  264. const propertyNode = property.node
  265. const firstUnorderedPropertyNode = firstUnorderedProperty.node
  266. const hasSideEffectsPossibility = propertiesNodes
  267. .slice(
  268. propertiesNodes.indexOf(firstUnorderedPropertyNode),
  269. propertiesNodes.indexOf(propertyNode) + 1
  270. )
  271. .some(
  272. (property) =>
  273. !isNotSideEffectsNode(property, sourceCode.visitorKeys)
  274. )
  275. if (hasSideEffectsPossibility) {
  276. return
  277. }
  278. const afterComma = sourceCode.getTokenAfter(propertyNode)
  279. const hasAfterComma = isComma(afterComma)
  280. const beforeComma = sourceCode.getTokenBefore(propertyNode)
  281. const codeStart = beforeComma.range[1] // to include comments
  282. const codeEnd = hasAfterComma
  283. ? afterComma.range[1]
  284. : propertyNode.range[1]
  285. const removeStart = hasAfterComma
  286. ? codeStart
  287. : beforeComma.range[0]
  288. yield fixer.removeRange([removeStart, codeEnd])
  289. const propertyCode =
  290. sourceCode.text.slice(codeStart, codeEnd) +
  291. (hasAfterComma ? '' : ',')
  292. const insertTarget = sourceCode.getTokenBefore(
  293. firstUnorderedPropertyNode
  294. )
  295. yield fixer.insertTextAfter(insertTarget, propertyCode)
  296. }
  297. })
  298. }
  299. })
  300. }
  301. return utils.executeOnVue(context, (obj) => {
  302. checkOrder(obj.properties)
  303. })
  304. }
  305. }