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 Feb 1, 2021
1 parent f1c093a commit 9bdc2f7
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 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,38 @@
import svelteDoc from 'sveltedoc-parser';

import dedent from 'ts-dedent';
import * as path from 'path';

// From https://github.com/sveltejs/svelte/blob/8db3e8d0297e052556f0b6dde310ef6e197b8d18/src/compiler/compile/utils/get_name_from_filename.ts
// Copied because it is not exported from the compiler
function getNameFromFilename(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 +57,12 @@ export default async function svelteDocgen(source: string) {
// populate filename in docgen
componentDoc.name = path.basename(file);

const componentName = path.parse(resource).name;
const componentName = getNameFromFilename(resource);

docgen = dedent`
docgen = `
${componentName}.__docgen = ${JSON.stringify(componentDoc)};
`;
${componentName}.__docgen = ${JSON.stringify(componentDoc)};
`;
} catch (error) {
console.error(error);
}
Expand Down

0 comments on commit 9bdc2f7

Please sign in to comment.