You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Storybook Canvas报错:ReferenceError: react is not defined 求助

解决Gatsby集成Storybook时Canvas预览报react is not defined的问题

react is not defined
ReferenceError: react is not defined
at react-dom/client (http://localhost:6006/main.iframe.bundle.js:1970:18)
at webpack_require (http://localhost:6006/runtime~main.iframe.bundle.js:28:33)
at fn (http://localhost:6006/runtime~main.iframe.bundle.js:339:21)
at webpack_require.t (http://localhost:6006/runtime~main.iframe.bundle.js:106:38)

可能的原因与修复步骤

1. 启用Gatsby Storybook官方预设

该报错通常是Storybook未正确适配Gatsby的React依赖配置导致的,优先检查是否安装并启用官方预设:

  • 安装预设(未安装时执行):
    npm install @storybook/preset-gatsby --save-dev
    
  • 修改.storybook/main.js,将预设添加到addons列表:
    module.exports = {
      stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
      addons: [
        "@storybook/addon-links",
        "@storybook/addon-essentials",
        "@storybook/preset-gatsby" // 确认该行存在
      ],
    };
    

2. 手动配置webpack全局注入React

若预设无效,通过webpack配置将React设为全局变量,让Canvas的iframe环境能正确识别:

  • 创建或修改.storybook/webpack.config.js:
    const webpack = require('webpack');
    
    module.exports = async ({ config }) => {
      config.plugins.push(
        new webpack.ProvidePlugin({
          React: 'react',
        })
      );
      return config;
    };
    

3. 清除缓存并重启Storybook

缓存可能导致配置不生效,执行以下操作:

  • 清除Storybook缓存:
    npx storybook build --clean
    
  • 重启Storybook服务:
    npm run storybook
    

4. 检查React版本一致性

确保项目中react和react-dom版本统一,避免依赖冲突:

npm ls react react-dom

若存在版本不一致,重新安装指定版本:

npm install react@<你的版本号> react-dom@<你的版本号> --save

内容的提问来源于stack exchange,提问作者Alex Karpov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:55:16