Storybook + Vite + Svelte + Typescript : Typescript not being processed in `*.stories.svelte`

Viewed 1528

I have been setting up storybook with Vite, Svelte and Typescript. It basically works fine except the Typescript part in the stories. For some reason Typescript preprocessing is being ignored in my *.stories.svelte files (in the component files it works fine).

I keep getting errors like this:

[vite] Internal server error: Unexpected token
  Plugin: storybook-addon-svelte-csf
  File: C:/projects/personal/exif-renamer/src/ui/1_globals/theme/font.stories.svelte
  2:     import { Meta,Story,Template } from '@storybook/addon-svelte-csf';
  3:     import { css } from '~/ui/1_globals/core/css';
  4:     import type { FontType } from './font';
                     ^
  5:     import { font } from './font';

For a *.stories.svelte file that has a script tag like this:

<script lang="ts">
    import { Meta,Story,Template } from '@storybook/addon-svelte-csf';
    import { css } from '~/ui/1_globals/core/css';
    import type { FontType } from './font';
    import { font } from './font';

    const cn = (type: FontType) => css`${font(type)}`;
</script>

My .storybook/main.js (where I have tried to force svelte preprocessing):

const { resolve } = require('path');
const { svelte } = require('@sveltejs/vite-plugin-svelte');
const { typescript: svelteTS } = require('svelte-preprocess');

module.exports = {
  stories: [resolve('src/**/*.stories.@(ts|svelte)')],
  addons: ['@storybook/addon-essentials', '@storybook/addon-svelte-csf'],
  core: {
    builder: 'storybook-builder-vite',
  },
  async viteFinal(config) {
    const { default: viteConfig } = await import('../vite.config.js');

    const svelteIndex = config.plugins.findIndex(
      ({ name }) => name === 'vite-plugin-svelte'
    );

    config.plugins[svelteIndex] = svelte({
      preprocess: [svelteTS()],
    });

    // customize the Vite config here
    config.resolve.alias = viteConfig.resolve.alias;

    // return the customized config
    return config;
  },
};

Any ideas why Typescript preprocessing is being ignored in my .stories files??

2 Answers

You'll need to add svelteOptions to your .storybook/main.cjs instead of patching in svelte support in viteFinal

svelteOptions: {
 preprocess: preprocess(), // or `preprocess: [svelteTS()]` in your case
},

That enables Typescript in both *.svelte and *.stories.svelte files.

Requires storybook-builder-vite version 0.1.16 or later.

It doesn't work with the webpack builder yet:
https://github.com/storybookjs/addon-svelte-csf/pull/41

It turned out that this was an actual bug, which should have been corrected with the latest version of Vite.

Related