Created
January 27, 2021 13:15
-
-
Save mizchi/c8758308ec24f9e51211c39a763ca6d1 to your computer and use it in GitHub Desktop.
This file contains 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
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