Skip to content

Commit

Permalink
Svelte: Fixes component name in docgen-loader
Browse files Browse the repository at this point in the history
  • Loading branch information
j3rem1e committed Jan 28, 2021
1 parent 8958e84 commit 26edaa0
Showing 1 changed file with 33 additions and 5 deletions.
38 changes: 33 additions & 5 deletions addons/docs/src/frameworks/svelte/svelte-docgen-loader.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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);
}
Expand Down

0 comments on commit 26edaa0

Please sign in to comment.