storybookjs / addon-svelte-csf

[Incubation] CSF using Svelte components.
MIT License
98 stars 29 forks source link

[Bug] svelte-stories-loader doesn't preprocess stories when using Webpack #168

Open vadirn opened 5 months ago

vadirn commented 5 months ago

Describe the bug

When using webpack5. https://github.com/storybookjs/addon-svelte-csf/blob/afad5de52923b7246dc2a385511e715b7d841098/src/parser/svelte-stories-loader.ts#L47 just reads the file, extractStories expects preprocessed source. So if story uses typescript, storybook fails.

Steps to reproduce the behavior

Just try to use lang="ts" and a type in any stories.svelte file, when using svelte-webpack5.

Expected behavior

*.stories.svelte should also be preprocessed.

Additional context

I've tried to patch the loader to make it work, but it also requires modifying storybook's webpack config. I'm not sure what's the proper way to pass svelte-webpack5 options to the loader config by default here: https://github.com/storybookjs/addon-svelte-csf/blob/afad5de52923b7246dc2a385511e715b7d841098/src/preset/index.ts#L12

And here is what I ended up modifying:

async function transformSvelteStories(code) {
    const options = this.getOptions();
    // @ts-ignore eslint-disable-next-line no-underscore-dangle
    const { resource } = this._module;
    const componentName = getNameFromFilename(resource);
    const source = readFileSync(resource).toString();
    // PREPROCESS -> 
    const { code: processedSource } = await svelte.preprocess(source, options.preprocess, { filename: options.filename});
    const storiesDef = extractStories(processedSource);
    const { stories } = storiesDef;
    const storyDef = Object.entries(stories)
        .filter(([, def]) => !def.template)
        .map(([id]) => `export const ${id} = __storiesMetaData.stories[${JSON.stringify(id)}]`)
        .join('\n');
    const metaExported = code.includes('export { meta }');
    const codeWithoutDefaultExport = code.replace('export default ', '//export default').replace('export { meta };', '// export { meta };');
    return `${codeWithoutDefaultExport}
    const { default: parser } = require('${parser}');
    const __storiesMetaData = parser(${componentName}, ${JSON.stringify(storiesDef)}${metaExported ? ', meta' : ''});
    export default __storiesMetaData.meta;
    ${storyDef};
  `;
}