From e080ce5410468ff6659b5a06a390a6f818216a38 Mon Sep 17 00:00:00 2001 From: qmhc <544022268@qq.com> Date: Tue, 30 Jul 2024 23:35:36 +0800 Subject: [PATCH] fix: more accurately generate index file fix #345 --- src/plugin.ts | 14 ++++++++++---- src/transform.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/plugin.ts b/src/plugin.ts index 21363a4..76f74ad 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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, @@ -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) diff --git a/src/transform.ts b/src/transform.ts index 72a9c91..0215981 100644 --- a/src/transform.ts +++ b/src/transform.ts @@ -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)