Search code examples
reactjsstorybookvite

Storybook with Vite error: fn.apply is not a function


I'm refactoring a React webapp from CRA to using Vite and having issues with Storybook. The storybook's GUI opens, and I see a list of stories on the left panel. But whichever story I choose I get an error TypeError: fn.apply is not a function in Canvas tab like shown here: enter image description here

I found a similar issue on Storybook's GitHub, and tried to change names StorybookName to storybookName in all the stories, also checked all the React components in the stories to make sure all of them are correctly defined as functions.

When it was using CRA storybook worked fine, but with Vite it's not working. Maybe I'm missing some configuration for Vite, so here's my vite.config.js as well:

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import svgrPlugin from 'vite-plugin-svgr';

const path = require('path');

export default defineConfig({
  esbuild: {
    jsxFactory: 'jsx',
    jsxInject: `import { jsx } from '@emotion/react'`,
  },
  optimizeDeps: {
    include: ['@emotion/react'],
  },
  plugins: [
    react({
      jsxImportSource: '@emotion/react',
      babel: {
        plugins: ['@emotion/babel-plugin'],
      },
    }),
    svgrPlugin({
      svgrOptions: {
        icon: true,
      },
    }),
  ],
});

And here's main.js from storybook:

const path = require('path');
const svgrPlugin = require('vite-plugin-svgr');

module.exports = {
  core: {
    builder: 'storybook-builder-vite',
  },
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: ['@storybook/addon-links', '@storybook/addon-essentials'],
  viteFinal: (config) => {
    return {
      ...config,
      plugins: [
        ...config.plugins,
        svgrPlugin({
          svgrOptions: {
            icon: true,
          },
        }),
      ],
    };
  },
};

In Chrome Dev Tools I get this error: enter image description here


Solution

  • I found the reason and it appears that all the configurations I had were correct. The problem was in the way how I aplied one of the decorators for Storybook. Basically, I wasn't correctly exporting one of the decorators and therefore was applying undefined instead of a decorator.

    So, for whoever faces this issue, please note that it's most of the time a problem with syntax. Check all your functions, components, decorators and so on and make sure they are all correctly defined and exported.

    The error message itself doesn't give any clue where to dig, which is a big shame, so this one is pretty tough to debug.