Skip to content

Commit

Permalink
fix: more accurately generate index file
Browse files Browse the repository at this point in the history
fix #354
  • Loading branch information
qmhc committed Jul 30, 2024
1 parent 1935414 commit 6a725a3
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import debug from 'debug'
import { cyan, green, yellow } from 'kolorist'
import { rollupDeclarationFiles } from './rollup'
import { JsonResolver, SvelteResolver, VueResolver, parseResolvers } from './resolvers'
import { hasExportDefault, normalizeGlob, transformCode } from './transform'
import { hasExportDefault, hasNamedExport, normalizeGlob, transformCode } from './transform'
import {
editSourceMapDir,
ensureAbsolute,
Expand Down Expand Up @@ -637,10 +637,16 @@ export function dtsPlugin(options: PluginOptions = {}): import('vite').Plugin {
fromPath = fromPath.replace(dtsRE, '')
fromPath = fullRelativeRE.test(fromPath) ? fromPath : `./${fromPath}`

let content = `export * from '${fromPath}'\n`
let content = ''

if (emittedFiles.has(sourceEntry) && hasExportDefault(emittedFiles.get(sourceEntry)!)) {
content += `import ${libName} from '${fromPath}'\nexport default ${libName}\n`
if (emittedFiles.has(sourceEntry)) {
if (hasNamedExport(emittedFiles.get(sourceEntry)!)) {
content += `export * from '${fromPath}'\n`
}

if (hasExportDefault(emittedFiles.get(sourceEntry)!)) {
content += `import ${libName} from '${fromPath}'\nexport default ${libName}\n`
}
}

await writeOutput(cleanPath(entryDtsPath), content, outDir)
Expand Down
31 changes: 31 additions & 0 deletions src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,37 @@ export function transformCode(options: {
}
}

export function hasNamedExport(content: string) {
const ast = ts.createSourceFile('a.ts', content, ts.ScriptTarget.Latest)

let has = false

walkSourceFile(ast, node => {
if (ts.isExportDeclaration(node) && node.exportClause && ts.isNamedExports(node.exportClause)) {
for (const element of node.exportClause.elements) {
if (element.name.escapedText !== 'default') {
has = true
break
}
}
} else if ('modifiers' in node && Array.isArray(node.modifiers) && node.modifiers.length > 1) {
for (let i = 0, len = node.modifiers.length; i < len; ++i) {
if (
node.modifiers[i].kind === ts.SyntaxKind.ExportKeyword &&
node.modifiers[i + 1]?.kind !== ts.SyntaxKind.DefaultKeyword
) {
has = true
break
}
}
}

return false
})

return has
}

export function hasExportDefault(content: string) {
const ast = ts.createSourceFile('a.ts', content, ts.ScriptTarget.Latest)

Expand Down

0 comments on commit 6a725a3

Please sign in to comment.