generated from storybookjs/addon-kit
-
Notifications
You must be signed in to change notification settings - Fork 32
/
svelte-stories-loader.ts
64 lines (48 loc) · 1.9 KB
/
svelte-stories-loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import dedent from 'ts-dedent';
import { readFileSync } from 'fs';
import { extractStories } from './extract-stories';
const parser = require.resolve('./collect-stories').replace(/[/\\]/g, '/');
// 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
export 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);
}
function transformSvelteStories(code: string) {
// eslint-disable-next-line no-underscore-dangle
const { resource } = this._module;
const componentName = getNameFromFilename(resource);
const source = readFileSync(resource).toString();
const stories = extractStories(source);
const storyDef = Object.entries(stories)
.filter(([, def]) => !def.template)
.map(([id]) => `export const ${id} = __storiesMetaData.stories[${JSON.stringify(id)}]`)
.join('\n');
const codeWithoutDefaultExport = code.replace('export default ', '//export default');
return dedent`${codeWithoutDefaultExport}
const { default: parser } = require('${parser}');
const __storiesMetaData = parser(${componentName}, ${JSON.stringify(stories)});
export default __storiesMetaData.meta;
${storyDef};
`;
}
export default transformSvelteStories;