Skip to content

Commit

Permalink
fix(findExports): normalize named exports
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Nov 11, 2021
1 parent 80d2868 commit b82d27b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
25 changes: 22 additions & 3 deletions src/analyze.ts
Expand Up @@ -25,12 +25,13 @@ export interface DynamicImport extends ESMImport {
}

export interface ESMExport {
_type?: 'declaration' | 'named' | 'default',
type: 'declaration' | 'named' | 'default',
code: string
start: number
end: number,
name?: string,
names?: string[]
names: string[]
}

export interface DeclarationExport extends ESMExport {
Expand Down Expand Up @@ -89,14 +90,32 @@ export function parseStaticImport (matched: StaticImport): ParsedStaticImport {
}

export function findExports (code: string): ESMExport[] {
// Find declarations like export const foo = 'bar'
const declaredExports = matchAll(EXPORT_DECAL_RE, code, { type: 'declaration' })

// Find named exports
const namedExports = matchAll(EXPORT_NAMED_RE, code, { type: 'named' })
for (const namedExport of namedExports) {
namedExport.names = namedExport.exports.split(/\s*,\s*/g).map(name => name.replace(/^.*?\sas\s/, '').trim())
}

const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, { type: 'default' })
// Find export default
const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, { type: 'default', name: 'default' })

// Merge and normalize exports
const exports = [].concat(declaredExports, namedExports, defaultExport)
for (const exp of exports) {
if (!exp.name && exp.names && exp.names.length === 1) {
exp.name = exp.names[0]
}
if (exp.name === 'default' && exp.type !== 'default') {
exp._type = exp.type
exp.type = 'default'
}
if (!exp.names && exp.name) {
exp.names = [exp.name]
}
}

return [].concat(declaredExports, namedExports, defaultExport)
return exports
}
3 changes: 2 additions & 1 deletion test/exports.test.mjs
Expand Up @@ -6,7 +6,8 @@ describe('findExports', () => {
'export function useA () { return \'a\' }': { name: 'useA', type: 'declaration' },
'export const useD = () => { return \'d\' }': { name: 'useD', type: 'declaration' },
'export { useB, _useC as useC }': { names: ['useB', 'useC'], type: 'named' },
'export default foo': { type: 'default' }
'export default foo': { type: 'default', name: 'default', names: ['default'] },
'export { foo as default }': { type: 'default', name: 'default', names: ['default'] }
}

describe('findExports', () => {
Expand Down

0 comments on commit b82d27b

Please sign in to comment.