Skip to content

Commit 2ac139a

Browse files
authored
refactor(prefer-use-template-ref): optimize performance and type safety (#2982)
1 parent 7523350 commit 2ac139a

File tree

2 files changed

+25
-32
lines changed

2 files changed

+25
-32
lines changed

.changeset/nine-zebras-rule.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"eslint-plugin-vue": patch
3+
---
4+
5+
Improved performance and type safety in `vue/prefer-use-template-ref`

lib/rules/prefer-use-template-ref.js

Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -8,40 +8,29 @@ const utils = require('../utils')
88

99
/**
1010
* @typedef ScriptRef
11-
* @type {{node: Expression, ref: string}}
11+
* @type {[string, CallExpression]}
1212
*/
1313

14-
/**
15-
* @param declarator {VariableDeclarator}
16-
* @returns {ScriptRef}
17-
* */
18-
function convertDeclaratorToScriptRef(declarator) {
19-
return {
20-
// @ts-ignore
21-
node: declarator.init,
22-
// @ts-ignore
23-
ref: declarator.id.name
24-
}
25-
}
26-
2714
/**
2815
* @param body {(Statement | ModuleDeclaration)[]}
2916
* @returns {ScriptRef[]}
3017
* */
3118
function getScriptRefsFromSetupFunction(body) {
32-
/** @type {VariableDeclaration[]} */
33-
const variableDeclarations = body.filter(
34-
(child) => child.type === 'VariableDeclaration'
35-
)
36-
const variableDeclarators = variableDeclarations.map(
37-
(declaration) => declaration.declarations[0]
38-
)
39-
const refDeclarators = variableDeclarators.filter((declarator) =>
40-
// @ts-ignore
41-
['ref', 'shallowRef'].includes(declarator.init?.callee?.name)
42-
)
19+
return body.flatMap((child) => {
20+
if (child.type === 'VariableDeclaration') {
21+
const declarator = child.declarations[0]
22+
23+
if (
24+
declarator.init?.type === 'CallExpression' &&
25+
declarator.init.callee?.type === 'Identifier' &&
26+
declarator.id.type === 'Identifier' &&
27+
['ref', 'shallowRef'].includes(declarator.init.callee.name)
28+
)
29+
return [[declarator.id.name, declarator.init]]
30+
}
4331

44-
return refDeclarators.map(convertDeclaratorToScriptRef)
32+
return []
33+
})
4534
}
4635

4736
/** @type {import("eslint").Rule.RuleModule} */
@@ -94,21 +83,20 @@ module.exports = {
9483
}),
9584
{
9685
'Program:exit'() {
86+
const scriptRefsMap = new Map(scriptRefs)
87+
9788
for (const templateRef of templateRefs) {
98-
const scriptRef = scriptRefs.find(
99-
(scriptRef) => scriptRef.ref === templateRef
100-
)
89+
const scriptRef = scriptRefsMap.get(templateRef)
10190

10291
if (!scriptRef) {
10392
continue
10493
}
10594

10695
context.report({
107-
node: scriptRef.node,
96+
node: scriptRef,
10897
messageId: 'preferUseTemplateRef',
10998
data: {
110-
// @ts-ignore
111-
name: scriptRef.node?.callee?.name
99+
name: /** @type {Identifier} */ (scriptRef.callee).name
112100
}
113101
})
114102
}

0 commit comments

Comments
 (0)