Updated componentLoader and vite to load any folder depth

This commit is contained in:
Samuel Andert 2023-07-24 09:39:33 +02:00
parent f75268a1d1
commit a572099312
6 changed files with 36 additions and 14 deletions

View File

@ -0,0 +1,10 @@
import componentNames from 'virtual:components-list';
const components = {};
componentNames.forEach(path => {
const name = path.split('/').pop(); // Extract just the file name from the path
components[name] = () => import( /* @vite-ignore */ `/src/lib/components/${path}.svelte`);
});
export default components;

View File

@ -1,9 +0,0 @@
import componentNames from 'virtual:components-list';
const components = {};
componentNames.forEach(name => {
components[name] = () => import(`$lib/components/${name}.svelte`);
});
export default components;

View File

@ -2,7 +2,6 @@
import { onMount } from 'svelte';
import { checkAndSignAuthMessage } from '@lit-protocol/lit-node-client';
import { LOCAL_STORAGE_KEYS } from '@lit-protocol/constants';
import Send from '$lib/Send.svelte';
let authSig = null;
let error = null;

View File

@ -1,6 +1,6 @@
<script lang="ts">
import Composite from './Composite.svelte'; // Recursive import
import components from '$lib/components.ts';
import components from '$lib/componentLoader';
import { getContextStore } from '$lib/stores/contextStore.ts';
export let componentsData = {

View File

@ -3,6 +3,22 @@ import { defineConfig } from 'vite';
import * as fs from 'fs';
import { resolve } from 'path';
// Utility function to get all .svelte files from a directory recursively
function getRecursiveSvelteFiles(dir) {
const dirents = fs.readdirSync(dir, { withFileTypes: true });
const files = Array.from(dirents).flatMap((dirent) => {
const res = resolve(dir, dirent.name);
if (dirent.isDirectory()) {
return getRecursiveSvelteFiles(res);
} else if (res.endsWith('.svelte')) {
return [res];
} else {
return [];
}
});
return files;
}
export default defineConfig({
plugins: [
sveltekit(),
@ -15,9 +31,15 @@ export default defineConfig({
load(id) {
if (id === 'virtual:components-list') {
const componentsDir = resolve(__dirname, 'src/lib/components');
const components = fs.readdirSync(componentsDir)
.filter(f => f.endsWith('.svelte'))
.map(f => f.replace('.svelte', ''));
const componentsFiles = getRecursiveSvelteFiles(componentsDir);
const components = componentsFiles.map(file =>
file
.replace(componentsDir, '')
.replace(/\.svelte$/, '')
.replace(/\\/g, '/') // Fix Windows path separators
.slice(1) // Remove leading "/"
);
return `export default ${JSON.stringify(components)};`;
}