- 
          
 - 
                Notifications
    
You must be signed in to change notification settings  - Fork 695
 
Add new rule: vue/define-macros-order (#1855) #1856
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 1 commit
      Commits
    
    
            Show all changes
          
          
            8 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      2d6114b
              
                Add new rule: vue/define-macros-order (#1855)
              
              
                edikdeisling c7d10ad
              
                Fix review comments
              
              
                edikdeisling 568917f
              
                Add review case
              
              
                edikdeisling 44621be
              
                Fix review comments
              
              
                edikdeisling 32203e8
              
                Fix review comments
              
              
                edikdeisling 066b35c
              
                Add semicolons
              
              
                edikdeisling 2a5ca8f
              
                Add some newline heuristics
              
              
                edikdeisling 19be4ae
              
                Fix slice review
              
              
                edikdeisling File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| --- | ||
| pageClass: rule-details | ||
| sidebarDepth: 0 | ||
| title: vue/define-macros-order | ||
| description: enforce order of `defineEmits` and `defineProps` compiler macros | ||
| --- | ||
| # vue/define-macros-order | ||
| 
     | 
||
| > enforce order of `defineEmits` and `defineProps` compiler macros | ||
| 
     | 
||
| - :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> ***This rule has not been released yet.*** </badge> | ||
| - :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule. | ||
| 
     | 
||
| ## :book: Rule Details | ||
| 
     | 
||
| This rule reports the situation when `defineProps` or `defineEmits` not on the top or have wrong order | ||
| 
     | 
||
| ## :wrench: Options | ||
| 
     | 
||
| ```json | ||
| { | ||
| "vue/define-macros-order": ["error", { | ||
| "order": [ "defineEmits", "defineProps" ] | ||
                
      
                  edikdeisling marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| }] | ||
| } | ||
| ``` | ||
| 
     | 
||
| - `order` (`string[]`) ... The order of defineEmits and defineProps macros | ||
| 
     | 
||
| ### `{ "order": [ "defineEmits", "defineProps" ] }` (default) | ||
| 
     | 
||
| <eslint-code-block fix :rules="{'vue/define-macros-order': ['error']}"> | ||
| 
     | 
||
| ```vue | ||
| <!-- ✓ GOOD --> | ||
| <script setup> | ||
| defineEmits(/* ... */) | ||
| defineProps(/* ... */) | ||
| </script> | ||
| ``` | ||
| 
     | 
||
| </eslint-code-block> | ||
| 
     | 
||
| <eslint-code-block fix :rules="{'vue/define-macros-order': ['error']}"> | ||
| 
     | 
||
| ```vue | ||
| <!-- ✗ BAD --> | ||
| <script setup> | ||
| defineProps(/* ... */) | ||
| defineEmits(/* ... */) | ||
| </script> | ||
| ``` | ||
| 
     | 
||
| </eslint-code-block> | ||
| 
     | 
||
| <eslint-code-block fix :rules="{'vue/define-macros-order': ['error']}"> | ||
| 
     | 
||
| ```vue | ||
| <!-- ✗ BAD --> | ||
| <script setup> | ||
| const bar = ref() | ||
| defineEmits(/* ... */) | ||
| defineProps(/* ... */) | ||
| </script> | ||
| ``` | ||
| 
     | 
||
| </eslint-code-block> | ||
| 
     | 
||
| ## :mag: Implementation | ||
| 
     | 
||
| - [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/define-macros-order.js) | ||
| - [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/define-macros-order.js) | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,248 @@ | ||
| /** | ||
| * @author Eduard Deisling | ||
| * See LICENSE file in root directory for full license. | ||
| */ | ||
| 'use strict' | ||
| 
     | 
||
| // ------------------------------------------------------------------------------ | ||
| // Requirements | ||
| // ------------------------------------------------------------------------------ | ||
| 
     | 
||
| const utils = require('../utils') | ||
| 
     | 
||
| // ------------------------------------------------------------------------------ | ||
| // Helpers | ||
| // ------------------------------------------------------------------------------ | ||
| 
     | 
||
| const MACROS_EMITS = 'defineEmits' | ||
| const MACROS_PROPS = 'defineProps' | ||
| const ORDER = [MACROS_EMITS, MACROS_PROPS] | ||
| const DEFAULT_ORDER = [MACROS_EMITS, MACROS_PROPS] | ||
                
      
                  edikdeisling marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| /** | ||
| * Get an index of the first statement after imports in order to place | ||
| * defineEmits and defineProps before this statement | ||
| * @param {Program} program | ||
| */ | ||
| function getStatementAfterImportsIndex(program) { | ||
| let index = -1 | ||
| 
     | 
||
| program.body.some((item, i) => { | ||
| index = i | ||
| return item.type !== 'ImportDeclaration' | ||
| }) | ||
| 
     | 
||
| return index | ||
| } | ||
| 
     | 
||
| /** | ||
| * We need to handle cases like "const props = defineProps(...)" | ||
| * Define macros must be used only on top, so we can look for "Program" type | ||
| * inside node.parent.type | ||
| * @param {CallExpression|ASTNode} node | ||
| * @return {ASTNode} | ||
| */ | ||
| function getDefineMacrosStatement(node) { | ||
| if (!node.parent) { | ||
| throw new Error('Macros has parent') | ||
| } | ||
| 
     | 
||
| if (node.parent.type === 'Program') { | ||
| return node | ||
| } | ||
| 
     | 
||
| return getDefineMacrosStatement(node.parent) | ||
| } | ||
| 
     | 
||
| // ------------------------------------------------------------------------------ | ||
| // Rule Definition | ||
| // ------------------------------------------------------------------------------ | ||
| 
     | 
||
| /** @param {RuleContext} context */ | ||
| function create(context) { | ||
| const scriptSetup = utils.getScriptSetupElement(context) | ||
| 
     | 
||
| if (!scriptSetup) { | ||
| return {} | ||
| } | ||
| 
     | 
||
| const sourceCode = context.getSourceCode() | ||
| const options = context.options | ||
| /** @type {[string, string]} */ | ||
| const order = (options[0] && options[0].order) || DEFAULT_ORDER | ||
                
      
                  edikdeisling marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| /** @type {Map<string, ASTNode>} */ | ||
| const macrosNodes = new Map() | ||
| 
     | 
||
| return utils.compositingVisitors( | ||
| utils.defineScriptSetupVisitor(context, { | ||
| onDefinePropsExit(node) { | ||
| macrosNodes.set(MACROS_PROPS, getDefineMacrosStatement(node)) | ||
| }, | ||
| onDefineEmitsExit(node) { | ||
| macrosNodes.set(MACROS_EMITS, getDefineMacrosStatement(node)) | ||
| } | ||
                
      
                  FloEdelmann marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| }), | ||
| { | ||
| 'Program:exit'(program) { | ||
| const shouldFirstNode = macrosNodes.get(order[0]) | ||
| const shouldSecondNode = macrosNodes.get(order[1]) | ||
| const firstStatementIndex = getStatementAfterImportsIndex(program) | ||
| const firstStatement = program.body[firstStatementIndex] | ||
| 
     | 
||
| // have both defineEmits and defineProps | ||
| if (shouldFirstNode && shouldSecondNode) { | ||
| const secondStatement = program.body[firstStatementIndex + 1] | ||
| 
     | 
||
| // need move only first | ||
| if (firstStatement === shouldSecondNode) { | ||
| reportNotOnTop(order[1], shouldFirstNode, firstStatement) | ||
| return | ||
| } | ||
| 
     | 
||
| // need move both defineEmits and defineProps | ||
| if (firstStatement !== shouldFirstNode) { | ||
| reportBothNotOnTop( | ||
| shouldFirstNode, | ||
| shouldSecondNode, | ||
| firstStatement | ||
| ) | ||
| return | ||
| } | ||
| 
     | 
||
| // need move only second | ||
| if (secondStatement !== shouldSecondNode) { | ||
| reportNotOnTop(order[1], shouldSecondNode, shouldFirstNode) | ||
| } | ||
| 
     | 
||
| return | ||
| } | ||
| 
     | 
||
| // have only first and need to move it | ||
| if (shouldFirstNode && firstStatement !== shouldFirstNode) { | ||
| reportNotOnTop(order[0], shouldFirstNode, firstStatement) | ||
| return | ||
| } | ||
| 
     | 
||
| // have only second and need to move it | ||
| if (shouldSecondNode && firstStatement !== shouldSecondNode) { | ||
| reportNotOnTop(order[1], shouldSecondNode, firstStatement) | ||
| } | ||
| } | ||
| } | ||
| ) | ||
| 
     | 
||
| /** | ||
| * @param {ASTNode} shouldFirstNode | ||
| * @param {ASTNode} shouldSecondNode | ||
| * @param {ASTNode} before | ||
| */ | ||
| function reportBothNotOnTop(shouldFirstNode, shouldSecondNode, before) { | ||
| context.report({ | ||
| node: shouldFirstNode, | ||
                
      
                  FloEdelmann marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| loc: shouldFirstNode.loc, | ||
| messageId: 'macrosNotOnTop', | ||
| data: { | ||
| macro: order[0] | ||
| }, | ||
| fix(fixer) { | ||
| return [ | ||
| ...moveNodeBefore(fixer, shouldFirstNode, before), | ||
| ...moveNodeBefore(fixer, shouldSecondNode, before) | ||
| ] | ||
| } | ||
| }) | ||
| } | ||
| 
     | 
||
| /** | ||
| * @param {string} macro | ||
| * @param {ASTNode} node | ||
| * @param {ASTNode} before | ||
| */ | ||
| function reportNotOnTop(macro, node, before) { | ||
| context.report({ | ||
| node, | ||
| loc: node.loc, | ||
| messageId: 'macrosNotOnTop', | ||
| data: { | ||
| macro | ||
| }, | ||
| fix(fixer) { | ||
| return moveNodeBefore(fixer, node, before) | ||
| } | ||
| }) | ||
| } | ||
| 
     | 
||
| /** | ||
| * Move one newline with "node" to before the "beforeNode" | ||
| * @param {RuleFixer} fixer | ||
| * @param {ASTNode} node | ||
| * @param {ASTNode} beforeNode | ||
| */ | ||
| function moveNodeBefore(fixer, node, beforeNode) { | ||
| const beforeNodeToken = sourceCode.getTokenBefore(node, { | ||
| includeComments: true | ||
| }) | ||
| const beforeNodeIndex = getNewLineIndex(node) | ||
| const textNode = sourceCode.getText(node, node.range[0] - beforeNodeIndex) | ||
| /** @type {[number, number]} */ | ||
| const removeRange = [beforeNodeToken.range[1], node.range[1]] | ||
| const index = getNewLineIndex(beforeNode) | ||
| 
     | 
||
| return [ | ||
| fixer.insertTextAfterRange([index, index], textNode), | ||
| fixer.removeRange(removeRange) | ||
| ] | ||
| } | ||
| 
     | 
||
| /** | ||
| * Get index of first new line before the "node" | ||
| * @param {ASTNode} node | ||
| * @return {number} | ||
| */ | ||
| function getNewLineIndex(node) { | ||
| const after = sourceCode.getTokenBefore(node, { includeComments: true }) | ||
| const hasWhitespace = node.loc.start.line - after.loc.end.line > 1 | ||
                
      
                  edikdeisling marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| if (!hasWhitespace) { | ||
| return after.range[1] | ||
| } | ||
| 
     | 
||
| return sourceCode.getIndexFromLoc({ | ||
| line: node.loc.start.line - 1, | ||
| column: 0 | ||
| }) | ||
| } | ||
| } | ||
| 
     | 
||
| module.exports = { | ||
| meta: { | ||
| type: 'layout', | ||
| docs: { | ||
| description: | ||
| 'enforce order of `defineEmits` and `defineProps` compiler macros', | ||
| categories: undefined, | ||
| url: 'https://eslint.vuejs.org/rules/define-macros-order.html' | ||
| }, | ||
| fixable: 'code', | ||
| schema: [ | ||
| { | ||
| type: 'object', | ||
| properties: { | ||
| order: { | ||
| type: 'array', | ||
| items: { | ||
| enum: Object.values(ORDER) | ||
| }, | ||
| uniqueItems: true, | ||
| additionalItems: false | ||
| } | ||
| }, | ||
| additionalProperties: false | ||
| } | ||
| ], | ||
| messages: { | ||
| macrosNotOnTop: '{{macro}} must be on top.' | ||
                
      
                  edikdeisling marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| } | ||
| }, | ||
| create | ||
| } | ||
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.