From c2282f36de046af65410400799a360cc7478452a Mon Sep 17 00:00:00 2001 From: EGOIST <0x142857@gmail.com> Date: Wed, 25 Aug 2021 19:36:42 +0800 Subject: [PATCH] feat: emitting declaration file for .ts files too also fixed a bug where "outDir" in tsconfig was ignored --- README.md | 2 +- examples/main.d.ts | 2 ++ examples/main.ts | 1 + src/index.ts | 32 +++++++++++++++++++++++--------- 4 files changed, 27 insertions(+), 10 deletions(-) create mode 100644 examples/main.d.ts create mode 100644 examples/main.ts diff --git a/README.md b/README.md index 0750cd2..096c638 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ vue-dts-gen src/App.vue # Emits dist/App.d.ts # Or glob patterns -vue-dts-gen "src/*.vue" +vue-dts-gen "src/*.{ts,vue}" # Emits dist/*.d.ts ``` diff --git a/examples/main.d.ts b/examples/main.d.ts new file mode 100644 index 0000000..0a065dc --- /dev/null +++ b/examples/main.d.ts @@ -0,0 +1,2 @@ +declare const _default: 123; +export default _default; diff --git a/examples/main.ts b/examples/main.ts new file mode 100644 index 0000000..05e0871 --- /dev/null +++ b/examples/main.ts @@ -0,0 +1 @@ +export default 123; diff --git a/src/index.ts b/src/index.ts index 477777c..2249770 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ import path from 'path' import fs from 'fs' -import { Project, SourceFile } from 'ts-morph' +import { Project, SourceFile, CompilerOptions } from 'ts-morph' import glob from 'fast-glob' import resolveFrom from 'resolve-from' @@ -28,14 +28,17 @@ export async function build({ input, outDir }: Options) { const tsConfigFilePath = fs.existsSync('tsconfig.json') ? 'tsconfig.json' : undefined + const compilerOptions: CompilerOptions = { + allowJs: true, + declaration: true, + emitDeclarationOnly: true, + noEmitOnError: true, + } + if (outDir) { + compilerOptions.outDir = outDir + } const project = new Project({ - compilerOptions: { - allowJs: true, - declaration: true, - emitDeclarationOnly: true, - noEmitOnError: true, - outDir, - }, + compilerOptions, tsConfigFilePath, skipAddingFilesFromTsConfig: true, }) @@ -46,6 +49,17 @@ export async function build({ input, outDir }: Options) { await Promise.all( files.map(async (file) => { const content = await fs.promises.readFile(file, 'utf8') + if (file.endsWith('.ts')) { + const sourceFile = project.createSourceFile( + path.relative(process.cwd(), file), + content, + { + overwrite: true, + }, + ) + sourceFiles.push(sourceFile) + return + } const sfc = vueCompiler.parse(content) const { script, scriptSetup } = sfc.descriptor if (script || scriptSetup) { @@ -74,7 +88,7 @@ export async function build({ input, outDir }: Options) { const diagnostics = project.getPreEmitDiagnostics() console.log(project.formatDiagnosticsWithColorAndContext(diagnostics)) - project.emitToMemory() + const emitted = project.emitToMemory() for (const sourceFile of sourceFiles) { const emitOutput = sourceFile.getEmitOutput()