简体   繁体   中英

Error with Storybook: Can't resolve 'react-chartjs-2'

I am using react-chartjs-2 in my next.js project and it works well when running the project. However, when I try to run Storybook , I get this error:

    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

This is the Chart component.

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;

In my package.json, I have

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

Why is it giving me this error?

I had this issue as well. I resolved it by updating storybooks main.js file. Under the WebpackFinal I added a alias for react-chartjs-2 that looks like this

// project/.storybook/main.js

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM