Using vite plugins with Storybook and SvelteKit

Viewed 1096

I have successfully set up @poppanator/sveltekit-svg with SvelteKit using the following configuration (svelte.config.js):

import preprocess from 'svelte-preprocess';
import svg from '@poppanator/sveltekit-svg';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    // Consult https://github.com/sveltejs/svelte-preprocess
    // for more information about preprocessors
    preprocess: preprocess(),

    kit: {
        // hydrate the <div id="svelte"> element in src/app.html
        target: '#svelte',
        vite: {
            plugins: [svg()]
        }
    }
};

export default config;

This works when running the SvelteKit project using npm run dev. However, I cannot get the svg plugin to work inside Storybook.

I have the following Storybook configuration (.storybook/main.cjs):

module.exports = {
  "stories": [
    "../src/**/*.stories.mdx",
    "../src/**/*.stories.@(js|jsx|ts|tsx|svelte)"
  ],
  "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-svelte-csf"
  ],
  "core": {
    "builder": "storybook-builder-vite"
  },
  "svelteOptions": { 
    preprocess: import("../svelte.config.js").preprocess 
  }
}

When importing SVG files in Storybook stories (or in components used by the stories), only the file path of the SVG file is returned. When importing SVG files inside a SvelteKit route, a Svelte component is returned as it should be.

I have tried this with Storybook 6.3.10 and 6.4.0-beta.7 with storybook-builder-vite (0.1.0).

How should this go together to make SVG imports work inside Storybook?

1 Answers

While SvelteKit uses Vite, Storybook uses Webpack.

To get svg imports working you'll need to find a loader for webpack that behaves similar to the @poppanator/sveltekit-svg plugin and add that to your storybook configuration.

I'm not sure similar loader exists (yet), depending on your usage, renaming the .svg files to .svelte could be an alternative

Related