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

React+Storybook遇TS2307错误:无法找到Button模块,Storybook能否解析?

Fixing TS2307: Cannot Find Module 'Button' in Storybook with Create React App

我之前也遇到过一模一样的问题!Storybook 默认不会自动继承你项目根目录 tsconfig 里的路径配置,这就是为什么 React 项目里能用绝对路径导入组件,但在 Storybook 中触发 TS2307 错误的核心原因。下面是我亲测有效的解决步骤:

1. 安装路径解析插件

首先需要安装 tsconfig-paths-webpack-plugin,它能让 Storybook 的 Webpack 配置识别你 tsconfig 里的自定义路径:

npm install tsconfig-paths-webpack-plugin --save-dev
# 或者用 yarn
yarn add tsconfig-paths-webpack-plugin -D

2. 配置 Storybook 的 Webpack 解析规则

在你的项目根目录下找到 .storybook/main.js(如果是 TypeScript 项目就是 main.ts),修改配置添加路径解析插件:

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: ['@storybook/addon-links', '@storybook/addon-essentials'],
  webpackFinal: async (config) => {
    // 注入 tsconfig 路径解析逻辑
    config.resolve.plugins = [
      ...(config.resolve.plugins || []),
      new TsconfigPathsPlugin({
        configFile: '../tsconfig.json', // 指向你项目根目录的 tsconfig 文件
      }),
    ];
    return config;
  },
};

3. 修正 tsconfig.json 的路径配置

你当前的 paths 配置是针对 src/* 的,但你要直接导入 Button,所以需要调整路径映射规则,同时确保 Storybook 的文件被 TypeScript 识别:

{
  "compilerOptions": { 
    "jsx": "react", 
    "esModuleInterop": true, 
    "moduleResolution": "node", 
    "strictNullChecks": true, 
    "rootDir": "src", 
    "baseUrl": "./", 
    "paths": { 
      "Button": [ "./src/Button/Button" ] // 直接映射到你的 Button 组件文件
      // 如果你的 Button 文件夹里有 index.js/ts 导出组件,可以写成 "Button": ["./src/Button"]
    } 
  }, 
  "include": [ 
    "./src", 
    "./src/**/*.ts", 
    "./src/**/*.tsx",
    "./.storybook/**/*" // 新增:让 TypeScript 识别 Storybook 相关文件
  ]
}

4. 确保组件正确导出

最后检查你的 Button.js(或 Button.tsx)是否正确导出了组件和类型:

// src/Button/Button.js
export const Button = ({ label }) => {
  return <button>{label}</button>;
};

// 如果是 TypeScript,导出类型
export type ButtonProps = {
  label: string;
};

完成以上步骤后,重启 Storybook 服务,你应该就能正常使用 import { Button, ButtonProps } from 'Button'; 而不会触发 TS2307 错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:03:36