Skip to content

Commit 4cc1a6d

Browse files
committed
Merge pull request #13760 from j3rem1e/svelte-13742
Svelte: Fixes component name in docgen-loader
1 parent 62f39ed commit 4cc1a6d

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

addons/docs/src/frameworks/svelte/svelte-docgen-loader.ts

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,38 @@
11
import svelteDoc from 'sveltedoc-parser';
2-
2+
import dedent from 'ts-dedent';
33
import * as path from 'path';
44

5+
// From https://github.com/sveltejs/svelte/blob/8db3e8d0297e052556f0b6dde310ef6e197b8d18/src/compiler/compile/utils/get_name_from_filename.ts
6+
// Copied because it is not exported from the compiler
7+
function getNameFromFilename(filename: string) {
8+
if (!filename) return null;
9+
10+
const parts = filename.split(/[/\\]/).map(encodeURI);
11+
12+
if (parts.length > 1) {
13+
const index_match = parts[parts.length - 1].match(/^index(\.\w+)/);
14+
if (index_match) {
15+
parts.pop();
16+
parts[parts.length - 1] += index_match[1];
17+
}
18+
}
19+
20+
const base = parts
21+
.pop()
22+
.replace(/%/g, 'u')
23+
.replace(/\.[^.]+$/, '')
24+
.replace(/[^a-zA-Z_$0-9]+/g, '_')
25+
.replace(/^_/, '')
26+
.replace(/_$/, '')
27+
.replace(/^(\d)/, '_$1');
28+
29+
if (!base) {
30+
throw new Error(`Could not derive component name from file ${filename}`);
31+
}
32+
33+
return base[0].toUpperCase() + base.slice(1);
34+
}
35+
536
/**
637
* webpack loader for sveltedoc-parser
738
* @param source raw svelte component
@@ -26,11 +57,12 @@ export default async function svelteDocgen(source: string) {
2657
// populate filename in docgen
2758
componentDoc.name = path.basename(file);
2859

29-
const componentName = path.parse(resource).name;
60+
const componentName = getNameFromFilename(resource);
61+
62+
docgen = dedent`
3063
31-
docgen = `
32-
${componentName}.__docgen = ${JSON.stringify(componentDoc)};
33-
`;
64+
${componentName}.__docgen = ${JSON.stringify(componentDoc)};
65+
`;
3466
} catch (error) {
3567
console.error(error);
3668
}

0 commit comments

Comments
 (0)