chore: dts function generator and comments

pull/81/head
moonrailgun 3 years ago
parent d55993ca13
commit ee0a0972b5

@ -1,6 +1,15 @@
import ts from 'typescript';
import fs from 'fs-extra';
/**
* Tools: https://ts-ast-viewer.com/
*/
interface ExportModuleItem {
name: string;
comment?: string;
}
/**
*
*/
@ -10,20 +19,53 @@ export function parseFile(filePath: string, options: ts.CompilerOptions) {
const service = ts.createLanguageService(host, ts.createDocumentRegistry());
const program = service.getProgram();
const exportModules: string[] = [];
program?.getSourceFile(filePath)?.forEachChild((node) => {
const exportModules: ExportModuleItem[] = [];
const sourceFile = program?.getSourceFile(filePath);
sourceFile?.forEachChild((node) => {
if (ts.isExportDeclaration(node)) {
// 如果为导出声明: export { foo } from 'foo'
node.exportClause?.forEachChild((exportSpec) => {
if (ts.isExportSpecifier(exportSpec)) {
exportModules.push(exportSpec.name.text);
exportModules.push({
name: exportSpec.name.text,
// comment:
});
}
});
} else if (isExportFunc(node)) {
// 如果是方法导出: export function foo() {}
if (node.name) {
exportModules.push({
name: node.name.text,
comment: getNodeComments(node),
});
}
}
});
return { exportModules };
}
function isExportFunc(node: ts.Node): node is ts.FunctionDeclaration {
if (ts.isFunctionDeclaration(node)) {
if (node.modifiers) {
return node.modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
}
}
return false;
}
function getNodeComments(node: ts.Node): string | undefined {
const comments = ts.getSyntheticLeadingComments(node);
if (!comments) {
return undefined;
}
return comments.map((c) => c.text).join('\n');
}
class FileServiceHost implements ts.LanguageServiceHost {
constructor(public filePath: string, private options: ts.CompilerOptions) {}

@ -1,2 +1,9 @@
export { foo } from '@/foo';
export { bar } from '@/bar';
/**
* Root export
*/
export function main() {
console.log('main');
}

Loading…
Cancel
Save