Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { PreprocessorGroup } from "svelte/types/compiler/preprocess";
import ts from "typescript";
import { preprocess } from "svelte/compiler";
async function getComponentProps(code: string) {
let interfaces: Array<{
identifier: string;
type: "number" | "string" | "boolean";
comment?: string;
}> = [];
const myPreprocess: PreprocessorGroup = {
script(input) {
const source = ts.createSourceFile(
"/index.tsx",
input.content,
ts.ScriptTarget.Latest
);
for (const stmt of source.statements) {
if (ts.isVariableStatement(stmt)) {
const hasExportModifier = stmt.modifiers?.some((mod) => {
return mod.kind === ts.SyntaxKind.ExportKeyword;
});
if (!hasExportModifier) continue;
// var = 0, let = 1, const = 2
if (stmt.declarationList.flags === 1) {
const m = stmt.getFullText(source).match(/\/\*\s(.*?)\s\*\//);
const comment = m?.[1];
// stmt.parent.
stmt.declarationList.forEachChild((child) => {
if (ts.isVariableDeclaration(child)) {
let type: "string" | "number" | "boolean";
if (child.type.kind === ts.SyntaxKind.NumberKeyword) {
type = "number";
}
if (child.type.kind === ts.SyntaxKind.StringKeyword) {
type = "string";
}
if (child.type.kind === ts.SyntaxKind.BooleanKeyword) {
type = "boolean";
}
interfaces.push({
identifier: child.name.getFullText(source),
type,
comment,
});
}
});
}
}
}
return {
code: input.content,
};
},
};
await preprocess(code, [myPreprocess]);
return interfaces;
}
const code = `
<script lang="ts">
/* var */
export let foo: string;
export let bar: number;
const baz = 1;
</script>
<div>{foo}:{bar}:{baz}</div>
`;
getComponentProps(code).then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment