Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot find module" when importing .csv file in Create React App

I am trying to import a CSV for use with the D3 library to create a chart within a Create React App project, but importing the file is throwing a "Cannot find module" error even though the path to the CSV file is correct.

I have a feeling this might be something to do with CRA's Webpack config under the hood but it looks like this is using the file loader so I'm not sure what the issue is. The data file is within CRA's src directory.

The console log in the code below is running with the correct data in, which means the data must be being accessed. The error is thrown after this (Although the path to the CSV is underlined red in my editor).

I am using TypeScript but I don't think this has anything to do with the problem.

import React from 'react';
import * as d3 from 'd3';
import CSVData from '../data/data.csv';

const BarChart: React.FC = () => {
  d3.csv(CSVData).then(res => {
    console.log(res);
  });
  return <div>Test</div>;
};

export default BarChart;
like image 535
Antfish Avatar asked Nov 06 '22 09:11

Antfish


1 Answers

CRA doesn't support importing .csv files. Without ejecting from CRA, your best option is to copy that file along with the results of yarn/npm build to your web server and then fetching it at runtime.

If that CSV is big (more than a few kb), then it is also the better option in terms of performance/code splitting.

like image 74
Nick Ribal Avatar answered Nov 13 '22 01:11

Nick Ribal