Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Svelte: Fixes component name in docgen-loader #13760

Merged
merged 1 commit into from
Feb 2, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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