Created
January 30, 2025 12:47
-
-
Save mizchi/945b0bb1850ae5b2e45ba75400437c4b to your computer and use it in GitHub Desktop.
Get .d.ts from input path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @prompt | |
* 指定されたTypeScriptのファイルから型定義とimportを抽出します | |
* $ deno run -A getDeclaration.ts <target> | |
*/ | |
import ts from "npm:[email protected]"; | |
export function getSourceSummary(filePath: string): string { | |
const compilerOptions: ts.CompilerOptions = { | |
declaration: true, | |
emitDeclarationOnly: true, | |
noEmitOnError: false, | |
target: ts.ScriptTarget.ESNext, | |
module: ts.ModuleKind.ESNext, | |
removeComments: false, | |
moduleResolution: ts.ModuleResolutionKind.NodeNext, | |
skipLibCheck: true, | |
allowJs: true, | |
checkJs: false, | |
strict: false, | |
noImplicitAny: false, | |
}; | |
const host = ts.createCompilerHost(compilerOptions); | |
let declarationOutput = ""; | |
host.writeFile = (fileName, contents) => { | |
if (fileName.endsWith(".d.ts")) { | |
declarationOutput = contents; | |
} | |
}; | |
const program = ts.createProgram({ | |
rootNames: [filePath], | |
options: compilerOptions, | |
host: host, | |
}); | |
program.emit(); | |
const source = program.getSourceFile(filePath)!; | |
const imports = source.statements.filter((stmt) => | |
ts.isImportDeclaration(stmt) | |
); | |
const printer = ts.createPrinter({ | |
removeComments: true, | |
}); | |
let outputText = ""; | |
if (imports.length > 0) { | |
outputText += "/// Imports\n"; | |
} | |
for (const stmt of imports) { | |
const importCode = printer.printNode(ts.EmitHint.Unspecified, stmt, source); | |
outputText += importCode + "\n"; | |
} | |
outputText += `/// Declaration\n${declarationOutput}`; | |
return outputText; | |
} | |
if (import.meta.main) { | |
const filePath = Deno.args[0]; | |
const summary = getSourceSummary(filePath); | |
console.log(summary); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment