Oops! Looks like an issue has popped up: using require() of an ES module is not supported when using recharts in combination with next.js

I've noticed some similar questions, but none of them seem to address my particular issue. I'm currently working on a webapp using next.js (with typescript). Within the app, I am utilizing recharts, however, I am encountering a compilation error:

Error: Must use import to load ES Module: project_path\node_modules\d3-shape\src\index.js
require() of ES modules is not supported.
require() of project_path\node_modules\d3-shape\src\index.js from project_path\node_modules\recharts\lib\shape\Symbols.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from project_path\node_modules\d3-shape\package.json.

Currently, I am using next.js 12, which natively supports ES modules without any additional configuration required. From my understanding, the root cause lies in the fact that d3-shape is imported as ESM while recharts, which depends on it, still uses require rather than imports (indeed, upon inspection, the compiled recharts package does utilize require()).

The issue seems to stem from the way recharts handles the import of d3 shapes. Any suggestions on how this can be resolved? It's puzzling that I appear to be the only one facing this dilemma.

One potential solution could involve forking recharts and ensuring it imports d3 shapes as esm modules (by adding type: "module" to the package.json file), although this may not be the most ideal approach.

Does anyone have any insights or ideas on how to tackle this problem? I'd prefer not to switch to alternative charting packages...

Answer №2

If you're encountering the same error but using Remix Run, check out this part of the documentation:

This is an example of how my configuration file appeared after making it compile:

//inside remix.config.js
/** @type {import('@remix-run/dev').AppConfig} */
module.exports = {
  ignoredRouteFiles: ["**/.*"],
  serverDependenciesToBundle: [
    "recharts",
    "d3-shape",
    "d3-scale",
    "d3-path",
    "d3-array",
    "d3-time",
    "d3-format",
    "d3-interpolate",
    "d3-time-format",
    "d3-color",
    "internmap",
  ],
};

Answer №3

Problem resolved thanks to implementing Dynamic Imports.

import dynamic from "next/dynamic";

const Info = dynamic(() => import("components/info/Info"), { ssr: false });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a task list without using JavaScript in the web browser and without relying on a database

Looking for some guidance on building a todo app for a job interview where JavaScript is disabled in the browser and no database can be used. Any JavaScript needs to be handled on the server side. I have some basic knowledge of node/express and serving H ...

What are the steps to conducting authenticated Supabase queries through a NextJS api route?

I'm encountering difficulties with the documentation and struggling to understand how I should authenticate my requests to the database. My Row Level Security settings only allow users to modify items that they own, identified by a column containing t ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Dialog box obscuring PrimeNG dropdown menu

I'm working on an Angular2 app that utilizes PrimeNG components. My issue arises when trying to include a dropdown inside a dialog box. Despite my implementation, the dropdown ends up being cut off due to the constraints of the dialog box, as visible ...

I am attempting to gather user input for an array while also ensuring that duplicate values are being checked

Can someone assist me with the following issue: https://stackblitz.com/edit/duplicates-aas5zs?file=app%2Fapp.component.ts,app%2Fapp.component.html I am having trouble finding duplicate values and displaying them below. Any guidance would be appreciated. I ...

What is the method for retrieving the index of an enum member in Typescript, rather than the member name?

Here is an example of how to work with enums in TypeScript: export enum Category { Action = 1, Option = 2, RealEstateFund = 3, FuturesContract = 4, ETFs = 5, BDRs = 6 } The following function can be used to retrieve the enum indexe ...

Arranging information within the Ngb-Accordion

Welcome to the code snippet showcasing how to create an accordion in Angular: <ngb-accordion [closeOthers]="false" activeIds="0"> <ng-container class="card" *ngFor="let post of Posts"> <ngb-panel title="{{post.title}} - ...

Getting Typescript Compiler to Recognize Global Types: Tips and Strategies

In the top level of my project, I have defined some global interfaces as shown below: globaltypes.ts declare global { my_interface { name:string } } However, when attempting to compile with ts-node, the compiler fails and displays the er ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Production environment experiencing issue with loading css for react-suneditor component

After following the instructions in the documentation, I successfully set up react-suneditor with dynamic loading to accommodate Next.js. Here is a snippet of my code: import React from 'react'; import dynamic from "next/dynamic"; impor ...

Efficiently Updating Property Values in Objects Using TypeScript and Loops

I have been looking into how to iterate or loop through a code snippet, and while I managed to do that, I am facing an issue where I cannot change the value of a property. Here is the snippet of code: export interface BaseOnTotalPaidFields { groupName ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

React-scripts is not recognizing tests that have the .tsx file extension

Currently in the process of converting my project to TypeScript, everything is almost working perfectly. The code builds without issues and renders correctly. The only hiccup I'm facing is with my tests. I've observed that when I change a test f ...

Issues with React Material UI Select functionality not performing as expected

I've been working on populating a Select Component from the Material UI library in React, but I'm facing an issue where I can't choose any of the options once they are populated. Below is my code snippet: import React, { useState, useEffect ...

Adding "data-cy" attribute to Next.js Link with Cypress

Is there a way to add data-cy if the Link does not have an <a> element? <Link href="/about/"> <span data-cy="nav-item">About</span> </Link> Link to article on using Cypress with Next.js for end-to-end ...

The callback URL for signing in is malfunctioning within NextAuth

My navigation component displays "Sign In" and "Sign Out" based on the active session status. The issue I am facing is with the callback after signing in. Upon signing out, the button successfully redirects to the Home Page. However, after a successful si ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Unable to update state in Next.js following async function execution

My Nextjs Form includes fields such as FirstName, Age, and a section to Upload Image. Once I populate the form and upload the image (saving the uploaded File in the state variable using URL.createObjectURL() which works fine), I aim to accomplish the follo ...