From 1e2db1bca27f2564b69206a4156a4e2bc720d07b Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Mon, 6 Sep 2021 23:43:48 +0800 Subject: [PATCH] fix: scan for template literal, close #37 --- src/core/identifiers.ts | 7 +++++-- test/identifiers.test.ts | 3 +++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/core/identifiers.ts b/src/core/identifiers.ts index 952ab0d..c64600b 100644 --- a/src/core/identifiers.ts +++ b/src/core/identifiers.ts @@ -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()) { for (let node of nodes) { @@ -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()) { +export function getIdentifierUsages(node?: Expression | TSType | SpreadElement | PrivateName | Statement | null, identifiers = new Set()) { if (!node) return identifiers @@ -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) // } diff --git a/test/identifiers.test.ts b/test/identifiers.test.ts index ee54658..822fc48 100644 --- a/test/identifiers.test.ts +++ b/test/identifiers.test.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-template-curly-in-string */ import { parse } from '@babel/parser' import { getIdentifierDeclarations, getIdentifierUsages } from '../src/core/identifiers' @@ -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) {