"Error: require() of ES Module" using Visx with Nextjs
Asked Answered
H

2

9

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

Heyduck answered 8/2, 2023 at 15:39 Comment(0)
M
1

TL;DR

This is an open issue with Visx 3.X.X and Next.

For now, downgrading Visx packages to their latest 2.X.X versions solves the problem.


Details

This appears to be an open issue with the Visx package at the time of this writing. Details here

In summary:

  • Visx 3 updates to the latest version of d3
  • The latest version of d3 is ESM-only, while Visx uses CommonJS
  • The Next build pipeline throws this error due to the mismatch

There are some workarounds mentioned in the issue involving Next 13's transpileModules; however, I was only able to solve the issue by downgrading all the Visx packages to their latest 2.X.X versions.

Mikesell answered 29/3, 2023 at 16:58 Comment(0)
L
0

TLDR: ensure that the versions of visx packages match.

I encountered a similar ESM error when I installed the @visx/stats package in my Next.js project. The error occurred when I tried to use the scaleBand function to draw boxplots from @visx/stats. After some investigation, I discovered that the cause of the error was the version mismatch between @visx/stats and @visx/visx packages.

I resolved the issue by downgrading the version of @visx/stats to match the version of @visx/visx that 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.

Lottielotto answered 28/2, 2023 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.