Skip to content

Commit

Permalink
feat: Add support for preprocessors inside *.stories.svelte
Browse files Browse the repository at this point in the history
  • Loading branch information
bfanger committed Feb 12, 2022
1 parent a9fcedb commit e2b27a7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
20 changes: 17 additions & 3 deletions packages/storybook-builder-vite/svelte/csf-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ import { getNameFromFilename } from '@storybook/addon-svelte-csf/dist/cjs/parser
import { readFileSync } from 'fs';
import { extractStories } from '@storybook/addon-svelte-csf/dist/cjs/parser/extract-stories';
const parser = require.resolve('@storybook/addon-svelte-csf/dist/esm/parser/collect-stories').replace(/[/\\]/g, '/');
import type { Options } from "@sveltejs/vite-plugin-svelte"
import * as svelte from "svelte/compiler"

export default {
export default function csfPlugin(svelteOptions?: Options) {
return {
name: 'storybook-addon-svelte-csf',
enforce: 'post',
transform(code: string, id: string) {
async transform(code: string, id: string) {
if (/.stories.svelte/.test(id)) {
const component = getNameFromFilename(id);
const source = readFileSync(id).toString();
let source = readFileSync(id).toString();
if (svelteOptions && svelteOptions.preprocess) {
source = (await svelte.preprocess(source, svelteOptions.preprocess)).code
}
const all = extractStories(source);
const { stories } = all;
const storyDef = Object.entries<any>(stories)
Expand All @@ -36,4 +42,12 @@ export default {
};
}
},
}
};

// dedent`${codeWithoutDefaultExport}
// const { default: parser } = require('${parser}');
// const __storiesMetaData = parser(${componentName}, ${JSON.stringify(storiesDef)});
// export default __storiesMetaData.meta;
// ${storyDef};
// `);
2 changes: 1 addition & 1 deletion packages/storybook-builder-vite/vite-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export async function pluginConfig(options: ExtendedOptions, _type: PluginConfig

try {
const csfPlugin = require('./svelte/csf-plugin').default;
plugins.push(csfPlugin);
plugins.push(csfPlugin(svelteOptions));
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') {
throw new Error(
Expand Down

0 comments on commit e2b27a7

Please sign in to comment.