From 6b5df10e5c346f173f0731a5f9d4dca77c99a4b4 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Tue, 20 Sep 2022 15:58:22 +0800 Subject: [PATCH] fix(findExports): correctly dedup named exports (#86) --- src/analyze.ts | 21 +++++++++++++-------- test/exports.test.ts | 17 ++++++++++++++++- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/analyze.ts b/src/analyze.ts index e27417b..954bf3a 100644 --- a/src/analyze.ts +++ b/src/analyze.ts @@ -135,15 +135,14 @@ export function findExports (code: string): ESMExport[] { return [] } - return exports.filter((exp, index, exports) => { + return exports // Filter false positive export matches - if (exportLocations && !_isExportStatement(exportLocations, exp)) { - return false - } + .filter(exp => !exportLocations || _isExportStatement(exportLocations, exp)) // Prevent multiple exports of same function, only keep latest iteration of signatures - const nextExport = exports[index + 1] - return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name - }) + .filter((exp, index, exports) => { + const nextExport = exports[index + 1] + return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name + }) } export function findExportNames (code: string): string[] { @@ -179,7 +178,13 @@ interface TokenLocation { } function _isExportStatement (exportsLocation: TokenLocation[], exp: ESMExport) { - return exportsLocation.some(location => exp.start <= location.start && exp.end >= location.end) + return exportsLocation.some((location) => { + // AST token inside the regex match + return exp.start <= location.start && exp.end >= location.end + // AST Token start or end is within the regex match + // return (exp.start <= location.start && location.start <= exp.end) || + // (exp.start <= location.end && location.end <= exp.end) + }) } function _tryGetExportLocations (code: string) { diff --git a/test/exports.test.ts b/test/exports.test.ts index a073320..8ff73f6 100644 --- a/test/exports.test.ts +++ b/test/exports.test.ts @@ -1,4 +1,3 @@ -import { join } from 'path' import { describe, it, expect } from 'vitest' import { ESMExport, findExports, findExportNames, resolveModuleExportNames } from '../src' @@ -130,6 +129,22 @@ describe('findExports', () => { const matches = findExports(code) expect(matches[0].names).toEqual(['foo', 'bar']) }) + + // https://github.com/nuxt/framework/issues/7658 + it('works the same with or without comment', () => { + const code1 = ` +export default function useMain() {} +` + const code2 = ` +export default function useMain() {} +// export default function useMain() {} +` + const matches1 = findExports(code1) + const matches2 = findExports(code2) + expect(matches1).toHaveLength(1) + expect(matches1[0].name).toEqual('default') + expect(matches2).toEqual(matches1) + }) }) describe('fineExportNames', () => {