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

使用npm link时Storybook加载Story失败:React未定义(React 18环境)

问题描述

我正在使用React 18构建一个UI组件库,其中导出了Button.tsx组件。为测试该Button组件的可用性,我通过npm link将其导入到同个UI组件库代码包内的另一个组件Test.tsx中,并为该组件创建了Story。

Test.tsx代码:

import Button from 'my-component-library'

const Test = (): JSX.Element => {
  return (
    <>
      <Button title='test' body='test' />
    </>
  )
}

export default Test

Test.tsx对应的Story代码:

import { Meta, Story } from '@storybook/react'
import React from 'react'

import Test from './Test'

export default {
  title: 'Test',
  component: Test,
} as Meta

export const Default: Story<any> = () => <Test />

查看Story时,Storybook UI显示错误:

Couldn't find story matching 'test--default'.

  • Are you sure a story with that id exists?
  • Please check your stories field of your main.js config.
  • Also check the browser console and terminal for error messages.

浏览器控制台输出错误:

Unexpected error while loading ./components/Test/Test.stories.tsx: react is not defined
ReferenceError: react is not defined

解决方案

核心原因是npm link导致React重复加载,同时可能伴随Storybook配置或组件导出路径问题,按以下步骤逐一排查解决:

  1. 解决React重复依赖冲突

    • 在UI组件库根目录执行命令,将测试项目的React链接到组件库,确保全局使用同一个React实例:
      npm link ../[测试项目路径]/node_modules/react
      npm link ../[测试项目路径]/node_modules/react-dom
      
    • 或者在组件库的package.json中,将react和react-dom设置为peerDependencies,强制使用宿主项目的React版本:
      "peerDependencies": {
        "react": "^18.0.0",
        "react-dom": "^18.0.0"
      }
      
  2. 修正Storybook配置

    • 打开.storybook/main.js,检查stories字段是否包含Test组件的Story文件,确保路径匹配:
      module.exports = {
        stories: ['../src/**/*.stories.tsx'], // 确保覆盖到你的Test.stories.tsx
        addons: ['@storybook/addon-essentials'],
        // 其他配置项
      }
      
    • 完全重启Storybook服务,让配置变更生效。
  3. 验证组件导入与导出路径

    • 确认组件库的package.json中main字段指向正确的导出入口,比如已打包后的文件路径:
      "main": "dist/index.js"
      
    • 如果组件库未打包,Test.tsx中的导入路径要直接指向Button组件的源文件,而非包名(避免npm link的路径混淆)。
  4. 清除缓存并重建依赖

    • 删除组件库和测试项目的node_modules、package-lock.json,重新执行npm install。
    • 执行npx storybook clean清除Storybook缓存,再重启服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:20:38