Skip to content

Commit

Permalink
fix(findExports): correctly dedup named exports (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Sep 20, 2022
1 parent 62f56fe commit 6b5df10
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
21 changes: 13 additions & 8 deletions src/analyze.ts
Expand Up @@ -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[] {
Expand Down Expand Up @@ -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) {
Expand Down
17 changes: 16 additions & 1 deletion 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'

Expand Down Expand Up @@ -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', () => {
Expand Down

0 comments on commit 6b5df10

Please sign in to comment.