Skip to content

Commit

Permalink
feat: add postinstall script to generate declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
CNSeniorious000 committed Aug 6, 2024
1 parent 16d09d1 commit d240af5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"lint": "eslint .",
"build": "vite build --sourcemap",
"preview": "vite preview",
"postinstall": "node src/lib/utils/generateDeclarations.js",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
Expand Down
27 changes: 27 additions & 0 deletions src/lib/utils/generateDeclarations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";

const srcPath = "./src";

const files = readdirSync(srcPath, { recursive: true, withFileTypes: true }).filter(file => file.isFile()).map(({ parentPath, name }) => `${parentPath}/${name}`);

for (const file of files) {
if (!file.endsWith(".ts") && !file.endsWith(".svelte"))
continue;

const content = readFileSync(file, "utf-8");
const lines = content.split("\n");

for (const line of lines) {
const importMatch = line.match(/import\s.*from\s*["'](.+)["']/);
if (importMatch) {
const modulePath = resolve(file, "..", importMatch[1]);

if (existsSync(modulePath) && statSync(modulePath).isDirectory() && !existsSync(join(modulePath, "index.ts"))) {
// generate dts
writeFileSync(join(modulePath, "index.d.ts"), `export default {} as {${readdirSync(modulePath).map(name => `\n ${JSON.stringify(name)}: string;`).join("")}\n}`, "utf-8");
console.warn(`Generated ${modulePath}/index.d.ts`);
}
}
}
}

0 comments on commit d240af5

Please sign in to comment.