I am using the Visx library to build charts in Nextjs. I am using the Visx scales, for which I import them as follows:
import { scaleBand, scaleLinear, scaleOrdinal } from "@visx/scale"
Internally, Visx uses d3's scales and is using "require" import to access them, so I get the following Nextjs error:
Error: require() of ES Module \node_modules\d3-scale\src\index.js from \node_modules\@visx\scale\lib\scales\band.js not supported. Instead change the require of index.js in \node_modules\@visx\scale\lib\scales\band.js to a dynamic import() which is available in all CommonJS modules.
I know the error is self-explanatory, but I would like to know if there is another solution besides changing the library's files or, in any case, what is the best one.
I also tried changing the imports of Visx scales, but I got another error:
Cannot use import statement outside a module
TLDR: ensure that the versions of
visxpackages match.I encountered a similar ESM error when I installed the
@visx/statspackage in my Next.js project. The error occurred when I tried to use thescaleBandfunction to draw boxplots from@visx/stats. After some investigation, I discovered that the cause of the error was the version mismatch between@visx/statsand@visx/visxpackages.I resolved the issue by downgrading the version of
@visx/statsto match the version of@visx/visxthat I was using. It's worth noting that this error may also occur if there are version mismatches with other packages you are using in your project.If you are experiencing a similar issue, I recommend checking for any version mismatches between your packages and ensuring that they are all compatible with each other. This may require adjusting the versions of some packages to match each other.
Hope this explanation helps anyone facing a similar problem.