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

Next.js项目中Storybook运行报错:无法解析react-chartjs-2及chart.js

问题描述

在Next.js项目中使用react-chartjs-2时项目运行正常,但启动Storybook时出现两个错误:

错误信息

ERROR in ./components/common/Chart/Chart.tsx
Module not found: Error: Can't resolve 'react-chartjs-2' in '/project/components/common/Chart'
 @ ./components/common/Chart/Chart.tsx 7:0-38 25:32-35
 @ ./components/common/Chart/index.ts
 @ ./components/common/index.ts
 @ ./common/theme/stories/Colors.stories.tsx
 @ ./common/theme/stories sync nonrecursive ^\.[\\/](?:(?!\.)(?=.)[^/]*?\.stories\.tsx)$

ERROR in ./node_modules/chart.js/dist/chart.js 561:17
Module parse failed: Unexpected token (561:17)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     };
| class DatasetController {
>  static defaults = {};
|  static datasetElementType = null;
|  static dataElementType = null;
 @ ./components/common/Chart/Chart.tsx 8:0-73 10:0-5 10:15-28 10:30-41 10:43-53
 @ ./components/common/Chart/index.ts
 @ ./components/common/index.ts
 @ ./common/theme/stories/Colors.stories.tsx
 @ ./common/theme/stories sync nonrecursive ^\.[\\/](?:(?!\.)(?=.)[^/]*?\.stories\.tsx)$
 @ ./generated-stories-entry.js

组件代码

import { Box } from '@components';
import { Bar } from 'react-chartjs-2';
import {
  Chart, CategoryScale, LinearScale, BarElement,
} from 'chart.js';

Chart.register(CategoryScale, LinearScale, BarElement);
const labels = ['1', '2', '3', '4', '5', '6'];
const data = {
  labels,
  datasets: [
    {
      borderWidth: 1,
    }
  ],
};

const ChartContainer = () => (
  <Box>
    <Bar
      data={data}
      options={{
        maintainAspectRatio: false,
      }}
    />
  </Box>
);

export default ChartContainer;

依赖版本

  • chart.js: ^4.0.1
  • react-chartjs-2: ^5.0.1
  • next: ^11.1.2
  • storybook: ^6.5.6
  • react: ^17.0.0

问题原因

1. 无法解析react-chartjs-2模块

Storybook的Webpack配置默认模块解析规则和Next.js不一致,大概率是这两种情况:

  • 项目配置了路径别名(比如@components),但Storybook的配置文件(.storybook/main.js)没同步配置对应的resolve.alias,导致模块解析路径出错;
  • 若项目是monorepo结构,Storybook未正确识别工作区的依赖链接,找不到react-chartjs-2包。

2. chart.js语法解析失败

chart.js v4版本使用了ES6+类静态属性(比如代码里的static defaults = {}),而你用的Storybook v6.5.6默认Webpack配置中,babel-loader会排除node_modules目录下的文件,不对其转译。你的项目环境(Webpack版本、babel配置)不支持未转译的ES6+语法,所以无法解析chart.js的代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:15:55