diff --git a/addons/docs/src/frameworks/svelte/svelte-docgen-loader.ts b/addons/docs/src/frameworks/svelte/svelte-docgen-loader.ts index 5ce93a7ac7a1..57eee85517be 100644 --- a/addons/docs/src/frameworks/svelte/svelte-docgen-loader.ts +++ b/addons/docs/src/frameworks/svelte/svelte-docgen-loader.ts @@ -1,7 +1,36 @@ import svelteDoc from 'sveltedoc-parser'; - import * as path from 'path'; +// From svelte/compiler/compile/utils but not exported +function get_name_from_filename(filename: string) { + if (!filename) return null; + + const parts = filename.split(/[/\\]/).map(encodeURI); + + if (parts.length > 1) { + const index_match = parts[parts.length - 1].match(/^index(\.\w+)/); + if (index_match) { + parts.pop(); + parts[parts.length - 1] += index_match[1]; + } + } + + const base = parts + .pop() + .replace(/%/g, 'u') + .replace(/\.[^.]+$/, '') + .replace(/[^a-zA-Z_$0-9]+/g, '_') + .replace(/^_/, '') + .replace(/_$/, '') + .replace(/^(\d)/, '_$1'); + + if (!base) { + throw new Error(`Could not derive component name from file ${filename}`); + } + + return base[0].toUpperCase() + base.slice(1); +} + /** * webpack loader for sveltedoc-parser * @param source raw svelte component @@ -26,11 +55,10 @@ export default async function svelteDocgen(source: string) { // populate filename in docgen componentDoc.name = path.basename(file); - const componentName = path.parse(resource).name; - + const componentName = get_name_from_filename(resource); docgen = ` - ${componentName}.__docgen = ${JSON.stringify(componentDoc)}; - `; +${componentName}.__docgen = ${JSON.stringify(componentDoc)}; +`; } catch (error) { console.error(error); }