Skip to content

Commit

Permalink
fix: scan for template literal, close #37
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Sep 6, 2021
1 parent c52503f commit 1e2db1b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/core/identifiers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PrivateName, Expression, Statement, SpreadElement, Node } from '@babel/types'
import { PrivateName, Expression, Statement, SpreadElement, Node, TSType } from '@babel/types'

export function getIdentifierDeclarations(nodes: Statement[], identifiers = new Set<string>()) {
for (let node of nodes) {
Expand Down Expand Up @@ -54,7 +54,7 @@ export function getIdentifierDeclarations(nodes: Statement[], identifiers = new
return identifiers
}

export function getIdentifierUsages(node?: Expression | SpreadElement | PrivateName | Statement | null, identifiers = new Set<string>()) {
export function getIdentifierUsages(node?: Expression | TSType | SpreadElement | PrivateName | Statement | null, identifiers = new Set<string>()) {
if (!node)
return identifiers

Expand Down Expand Up @@ -114,6 +114,9 @@ export function getIdentifierUsages(node?: Expression | SpreadElement | PrivateN
else if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') {
getIdentifierUsages(node.body, identifiers)
}
else if (node.type === 'TemplateLiteral') {
node.expressions.forEach(expr => getIdentifierUsages(expr, identifiers))
}
// else {
// console.log(node)
// }
Expand Down
3 changes: 3 additions & 0 deletions test/identifiers.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-template-curly-in-string */
import { parse } from '@babel/parser'
import { getIdentifierDeclarations, getIdentifierUsages } from '../src/core/identifiers'

Expand Down Expand Up @@ -51,6 +52,8 @@ describe('identifiers', () => {
['() => { foo() + bar; a }', ['foo', 'bar', 'a']],
['(function () { foo() + bar })', ['foo', 'bar']],
['function foobar() { return foo() + bar }', ['foo', 'bar']],
['`${foo}bar`', ['foo']],
['`${foo(zag)}` + bar', ['foo', 'zag', 'bar']],
]

for (const [input, output] of cases) {
Expand Down

0 comments on commit 1e2db1b

Please sign in to comment.