故事书错误:无法解决'react-chartjs-2'



我使用react-chartjs-2next.js项目,它在运行项目时运行良好。但是,当我尝试运行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

这是Chart组件。

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;

在我的包里。json中有

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

为什么给我这个错误?

我也有同样的两个问题。

第一个错误

第一个问题是storybook找不到react-chartjs-2模块:

我通过更新故事书main.js文件解决了这个问题。在WebpackFinal下面,我为react-chartjs-2添加了一个别名,看起来像这样

// project/.storybook/main.js
'react-chartjs-2': path.resolve(__dirname, '../node_modules/react-chartjs-2/dist/index.js')

第二个错误

第二个问题是storybook不知道如何解析chart.js中的static defaults = {}

我通过更新故事书main.js来解决这个问题,包括frameworkcore的属性。

// project/.storybook/main.js
framework: '@storybook/react',
core: {
builder: '@storybook/builder-webpack5'
}

我还必须安装下面列出的软件包

@storybook/builder-webpack5
@storybook/manager-webpack5

在这些更改之后,我能够运行storybook并查看我的图表。通过创建一个新项目并将storybook和chart.js安装到其中,以便唯一的东西是图表组件,然后我比较了该项目配置与我的其他项目配置之间的差异。

我希望这对你有帮助。

最新更新