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

Issue with loading local fonts in Storybook using Next.js 13, Tailwind, and Storybook 7

Initial Question: Everything in my setup is functioning properly, except for one issue: the custom fonts are not loading in Storybook. (The main concern revolves around the missing CSS variable, check the bottom section for details. I'm including al ...

Issue regarding retrieving the image using TypeScript from an external API

Hey developers! I'm facing an issue with importing images from an external API. I used the tag: <img src = {photos [0] .src} /> but it doesn't seem to recognize the .src property. Can anyone shed some light on how this is supposed to work? ...

What is the best way to eliminate tasks from a list in Angular?

I have been working on a scheduler tool that allows me to record the tasks I complete within a specific timeframe. These tasks are displayed in a list similar to a to-do list. One of the challenges I'm facing is removing individual items from the lis ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Trouble accessing Strapi CMS data on Next.js frontend using React.js

Currently, I am in the process of developing a website using Strapi as the CMS and Next.js(React) for the Frontend. The website features an image slider that includes an image, a headline, and a description. I am trying to retrieve these elements from my S ...

Error Passing Data to Child Component in Typescript on Next.JS 14 Compilation

Although there are many similar questions, I am struggling to make my code work properly. I recently started learning typescript and am having trouble passing data to the child component. While the code runs fine in development (no errors or warnings), i ...

Using Vue js and Typescript to automatically scroll to the bottom of a div whenever there are changes in

My goal is to automatically scroll to the bottom of a div whenever a new comment is added. Here's what I have been trying: gotoBottom() { let content = this.$refs.commentsWrapper; content.scrollTop = content.scrollHeight } The div containing ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Issue encountered: Cannot locate module: Error message - Unable to find 'stream' in 'C:devjszip-test ode_modulesjsziplib' folder

I am encountering an issue in my angular 7 application while using jszip v3.2.1. During the project build process (e.g., running npm start), I receive the following error message: ERROR in ./node_modules/jszip/lib/readable-stream-browser.js Module not fo ...

Determining the output type by considering the presence of optional parameters

function customFunction<T>(defaultValue?: T) { return defaultValue; } const definitelyNullOrUndefined = customFunction<string>(); // type: string | undefined const definitelyStringType = customFunction<string>('foobar'); // ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

What is the best way to transfer information between different pages in Next.js?

I am currently working on a Next.js app with multiple pages. One common element across all pages is a top bar that displays data fetched from an internal API using SWR. The challenge I face is obtaining the logged-in user's ID, which is required to fe ...

Utilizing Angular 11's HostListener to capture click events and retrieve the value of an object

Using the HostListener directive, I am listening for the click event on elements of the DOM. @HostListener('click', ['$event.target']) onClick(e) { console.log("event", e) } Upon clicking a button tag, the "e" object contains the fol ...

PrismaClient is currently incompatible with this browser environment and has been optimized for use in an unknown browser when performing updates

While attempting to update a single field in my database using server-actions and tanstackQuery, I encountered the following error message: Error: PrismaClient is unable to run in this browser environment, or has been bundled for the browser (running in ...

What's the best way to fix the issue of the "Warning: Each child in a list should have a unique "key" prop"?

Upon running "yarn run dev", an error message appears stating: Warning: Each child in a list should have a unique "key" prop. Check the top-level render call using . See https://reactjs.org/link/warning-keys for more information. at StarIcon at Product (w ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Potential absence of object.ts(2531)

Currently, I am working on a project using Node.js with Typescript. My task involves finding a specific MongoDB document, updating certain values within it, and then saving the changes made. However, when I try to save the updated document, an error is bei ...

Latest Angular 2 Release: Lack of visual updates following asynchronous data entry

Currently, I am working with Angular2-Beta1, However, the templating from the "*ngFor" is not working properly and is only displayed as <!--template bindings={}--> and not as <template ...></template> as described here on the Angular2 G ...