【问题标题】:Storybook with Vite error: fn.apply is not a function带有 Vite 错误的故事书:fn.apply 不是函数
【发布时间】:2022-01-22 00:10:28
【问题描述】:

我正在将 React webapp 从 CRA 重构为使用 Vite 并遇到 Storybook 的问题。故事书的 GUI 打开,我在左侧面板上看到一个故事列表。但无论我选择哪个故事,我都会在 Canvas 选项卡中收到错误 TypeError: fn.apply is not a function,如下所示:

我在 Storybook 的 GitHub 上发现了类似的问题,并尝试将所有故事中的名称 StorybookName 更改为 storybookName,还检查了故事中的所有 React 组件以确保它们都被正确定义为功能。

使用 CRA 故事书时效果很好,但使用 Vite 时就不行了。也许我缺少 Vite 的一些配置,所以这也是我的vite.config.js

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,
      },
    }),
  ],
});

这里是来自故事书的main.js

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,
          },
        }),
      ],
    };
  },
};

在 Chrome 开发工具中,我收到此错误:

【问题讨论】:

    标签: reactjs storybook vite


    【解决方案1】:

    我找到了原因,看来我的所有配置都是正确的。问题在于我如何为 Storybook 应用其中一个装饰器。基本上,我没有正确导出其中一个装饰器,因此应用了undefined 而不是装饰器。

    因此,对于遇到此问题的人,请注意大多数情况下是语法问题。检查所有函数、组件、装饰器等,确保它们都正确定义和导出。

    错误消息本身并没有提供任何线索,这是一个很大的耻辱,所以这个很难调试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2020-12-07
      • 2021-06-22
      • 2019-01-17
      • 1970-01-01
      • 2022-06-28
      • 2019-07-12
      相关资源
      最近更新 更多