forked from vuejs/eslint-plugin-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefer-use-template-ref.js
89 lines (80 loc) · 2.04 KB
/
prefer-use-template-ref.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* @author Thomasan1999
* See LICENSE file in root directory for full license.
*/
'use strict'
const utils = require('../utils')
/** @param expression {Expression | null} */
function expressionIsRef(expression) {
// @ts-ignore
return expression?.callee?.name === 'ref'
}
/** @type {import("eslint").Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'require using `useTemplateRef` instead of `ref` for template refs',
categories: undefined,
url: 'https://eslint.vuejs.org/rules/prefer-use-template-ref.html'
},
schema: [],
messages: {
preferUseTemplateRef: "Replace 'ref' with 'useTemplateRef'."
}
},
/** @param {RuleContext} context */
create(context) {
/** @type Set<string> */
const templateRefs = new Set()
/**
* @typedef ScriptRef
* @type {{node: Expression, ref: string}}
*/
/**
* @type ScriptRef[] */
const scriptRefs = []
return utils.compositingVisitors(
utils.defineTemplateBodyVisitor(
context,
{
'VAttribute[directive=false]'(node) {
if (node.key.name === 'ref' && node.value?.value) {
templateRefs.add(node.value.value)
}
}
},
{
VariableDeclarator(declarator) {
if (!expressionIsRef(declarator.init)) {
return
}
scriptRefs.push({
// @ts-ignore
node: declarator.init,
// @ts-ignore
ref: declarator.id.name
})
}
}
),
{
'Program:exit'() {
for (const templateRef of templateRefs) {
const scriptRef = scriptRefs.find(
(scriptRef) => scriptRef.ref === templateRef
)
if (!scriptRef) {
continue
}
context.report({
node: scriptRef.node,
messageId: 'preferUseTemplateRef'
})
}
}
}
)
}
}