|
| 1 | +// scripts/generate-index.ts |
| 2 | +import { readdirSync, statSync, writeFileSync } from "node:fs"; |
| 3 | +import { basename, join, relative } from "node:path"; |
| 4 | + |
| 5 | +const libDir = "src/lib"; |
| 6 | +const componentsDir = join(libDir, "components"); // Target only the components directory |
| 7 | +const indexFile = join(libDir, "index.ts"); |
| 8 | + |
| 9 | +function findSvelteFiles(dir: string): string[] { |
| 10 | + let svelteFiles: string[] = []; |
| 11 | + const items = readdirSync(dir); |
| 12 | + |
| 13 | + items.forEach((item) => { |
| 14 | + const fullPath = join(dir, item); |
| 15 | + const stat = statSync(fullPath); |
| 16 | + |
| 17 | + // Ignore node_modules or dist if they somehow end up here |
| 18 | + if (item === "node_modules" || item === "dist") { |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + if (stat.isDirectory()) { |
| 23 | + // Recursively search in subdirectories |
| 24 | + svelteFiles = svelteFiles.concat(findSvelteFiles(fullPath)); |
| 25 | + } else if (item.endsWith(".svelte")) { |
| 26 | + // Path relative to componentsDir |
| 27 | + svelteFiles.push(relative(componentsDir, fullPath)); |
| 28 | + } |
| 29 | + }); |
| 30 | + |
| 31 | + // Sort to ensure consistent order if duplicates exist |
| 32 | + return svelteFiles.sort(); |
| 33 | +} |
| 34 | + |
| 35 | +// Start the search from componentsDir |
| 36 | +const svelteFilesInComponents = findSvelteFiles(componentsDir); |
| 37 | + |
| 38 | +const exportedNames = new Set<string>(); // Keep track of names already exported |
| 39 | + |
| 40 | +const exports = svelteFilesInComponents |
| 41 | + .map((filePath) => { |
| 42 | + const name = basename(filePath, ".svelte"); |
| 43 | + |
| 44 | + // Only export if the name hasn't been used yet |
| 45 | + if (!exportedNames.has(name)) { |
| 46 | + exportedNames.add(name); // Mark name as used |
| 47 | + const importPath = join("components", filePath).replace(/\\\\/g, "/"); |
| 48 | + return `export { default as ${name} } from './${importPath}';`; |
| 49 | + } |
| 50 | + return null; // Skip duplicate |
| 51 | + }) |
| 52 | + .filter((line): line is string => line !== null); // Remove null entries |
| 53 | + |
| 54 | +// Write the file only if there are no duplicates |
| 55 | +writeFileSync( |
| 56 | + indexFile, |
| 57 | + `// this file is auto-generated — do not edit by hand\n${exports.join("\n")}\n`, |
| 58 | +); |
| 59 | + |
| 60 | +console.log( |
| 61 | + `Generated ${indexFile} with ${exports.length} unique exports from ./components. Duplicates were ignored.`, |
| 62 | +); |
0 commit comments