Skip to content

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

Open
@vadirn

Description

@vadirn

Describe the bug

When using webpack5.

const source = readFileSync(resource).toString();
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:

export function webpack(config) {

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};
  `;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    legacyRelated to the legacy version(s)

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions