order-in-components.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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', 'vue2-recommended'],
  193. url: 'https://eslint.vuejs.org/rules/order-in-components.html'
  194. },
  195. fixable: 'code', // null or "code" or "whitespace"
  196. hasSuggestions: true,
  197. schema: [
  198. {
  199. type: 'object',
  200. properties: {
  201. order: {
  202. type: 'array'
  203. }
  204. },
  205. additionalProperties: false
  206. }
  207. ],
  208. messages: {
  209. order:
  210. 'The "{{name}}" property should be above the "{{firstUnorderedPropertyName}}" property on line {{line}}.',
  211. reorderWithSideEffects:
  212. 'Manually move "{{name}}" property above "{{firstUnorderedPropertyName}}" property on line {{line}} (might break side effects).'
  213. }
  214. },
  215. /** @param {RuleContext} context */
  216. create(context) {
  217. const options = context.options[0] || {}
  218. /** @type {(string|string[])[]} */
  219. const order = options.order || defaultOrder
  220. /** @type {(string|string[])[]} */
  221. const extendedOrder = order.map(
  222. (property) =>
  223. (typeof property === 'string' && groups[property]) || property
  224. )
  225. const orderMap = getOrderMap(extendedOrder)
  226. const sourceCode = context.getSourceCode()
  227. /**
  228. * @param {string} name
  229. */
  230. function getOrderPosition(name) {
  231. const num = orderMap.get(name)
  232. return num == null ? -1 : num
  233. }
  234. /**
  235. * @param {RuleFixer} fixer
  236. * @param {Property} propertyNode
  237. * @param {Property} unorderedPropertyNode
  238. */
  239. function* handleFix(fixer, propertyNode, unorderedPropertyNode) {
  240. const afterComma = sourceCode.getTokenAfter(propertyNode)
  241. const hasAfterComma = isComma(afterComma)
  242. const beforeComma = sourceCode.getTokenBefore(propertyNode)
  243. const codeStart = beforeComma.range[1] // to include comments
  244. const codeEnd = hasAfterComma
  245. ? afterComma.range[1]
  246. : propertyNode.range[1]
  247. const removeStart = hasAfterComma ? codeStart : beforeComma.range[0]
  248. yield fixer.removeRange([removeStart, codeEnd])
  249. const propertyCode =
  250. sourceCode.text.slice(codeStart, codeEnd) + (hasAfterComma ? '' : ',')
  251. const insertTarget = sourceCode.getTokenBefore(unorderedPropertyNode)
  252. yield fixer.insertTextAfter(insertTarget, propertyCode)
  253. }
  254. /**
  255. * @param {(Property | SpreadElement)[]} propertiesNodes
  256. */
  257. function checkOrder(propertiesNodes) {
  258. const properties = propertiesNodes
  259. .filter(utils.isProperty)
  260. .map((property) => ({
  261. node: property,
  262. name:
  263. utils.getStaticPropertyName(property) ||
  264. (property.key.type === 'Identifier' && property.key.name) ||
  265. ''
  266. }))
  267. for (const [i, property] of properties.entries()) {
  268. const orderPos = getOrderPosition(property.name)
  269. if (orderPos < 0) {
  270. continue
  271. }
  272. const propertiesAbove = properties.slice(0, i)
  273. const unorderedProperties = propertiesAbove
  274. .filter(
  275. (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
  276. )
  277. .sort((p1, p2) =>
  278. getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
  279. )
  280. const firstUnorderedProperty = unorderedProperties[0]
  281. if (firstUnorderedProperty) {
  282. const line = firstUnorderedProperty.node.loc.start.line
  283. const propertyNode = property.node
  284. const firstUnorderedPropertyNode = firstUnorderedProperty.node
  285. const hasSideEffectsPossibility = propertiesNodes
  286. .slice(
  287. propertiesNodes.indexOf(firstUnorderedPropertyNode),
  288. propertiesNodes.indexOf(propertyNode) + 1
  289. )
  290. .some(
  291. (property) =>
  292. !isNotSideEffectsNode(property, sourceCode.visitorKeys)
  293. )
  294. context.report({
  295. node: property.node,
  296. messageId: 'order',
  297. data: {
  298. name: property.name,
  299. firstUnorderedPropertyName: firstUnorderedProperty.name,
  300. line
  301. },
  302. fix: hasSideEffectsPossibility
  303. ? undefined
  304. : (fixer) =>
  305. handleFix(fixer, propertyNode, firstUnorderedPropertyNode),
  306. suggest: hasSideEffectsPossibility
  307. ? [
  308. {
  309. messageId: 'reorderWithSideEffects',
  310. data: {
  311. name: property.name,
  312. firstUnorderedPropertyName: firstUnorderedProperty.name,
  313. line
  314. },
  315. fix: (fixer) =>
  316. handleFix(fixer, propertyNode, firstUnorderedPropertyNode)
  317. }
  318. ]
  319. : undefined
  320. })
  321. }
  322. }
  323. }
  324. return utils.compositingVisitors(
  325. utils.executeOnVue(context, (obj) => {
  326. checkOrder(obj.properties)
  327. }),
  328. utils.defineScriptSetupVisitor(context, {
  329. onDefineOptionsEnter(node) {
  330. if (node.arguments.length === 0) return
  331. const define = node.arguments[0]
  332. if (define.type !== 'ObjectExpression') return
  333. checkOrder(define.properties)
  334. }
  335. })
  336. )
  337. }
  338. }