Mixing ECMAScript and CommonJS modules is not allowed

I'm currently facing an issue while trying to incorporate a library into my NEXTjs-TypeScript project. It functions properly during development, but upon running npm run build, I encountered the following error:

    ./src/pages/_app.tsx:17:52
Type error: The current file is a CommonJS module that uses 'require' calls for imports; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. You may consider using dynamic 'import("@solana/wallet-adapter-react")' instead.
  To convert this file to an ECMAScript module, add the field `"type": "module"` to '/path/to/project/package.json'.

The problematic imports are as follows:

import { Meta } from "@lib/meta";
import { SigninOverview } from "src/layout/account/SigninOverview";
import { getCsrfToken, signIn, useSession } from "next-auth/react";
import { useWalletModal } from "@solana/wallet-adapter-react-ui"; // Fails to compile on `npm run build`
import { useWallet } from "@solana/wallet-adapter-react"; // Fails to compile on `npm run build`
import { SigninMessage } from "@lib/signinMessage";
import bs58 from "bs58";
import { AccountOverview } from "src/layout/account/AccountOverview";

I attempted using dynamic imports, but it disrupted the development process because it then required me to utilize await when importing components:

./lib/solana/index.ts:

export const walletAdapterReactUi = async () => {
    return await import("@solana/wallet-adapter-react-ui");
};

export const walletAdapterReact = async () => {
    return await import("@solana/wallet-adapter-react");
};

export const walletAdapterBase = async () => {
    return await import("@solana/wallet-adapter-base");
};

export const walletAdapterWallets = async () => {
    return await import("@solana/wallet-adapter-wallets");
};

./src/pages/_app.tsx

  21 | //import "./styles.css";
  22 |
> 23 | const App: React.FC<AppProps> = async ({ Component, pageProps }) => {
     |                                         ^
  24 |     const { WalletAdapterNetwork } = await walletAdapterBase();
  25 |     const network = WalletAdapterNetwork.Devnet;
  26 |     const { ConnectionProvider, WalletProvider } = await walletAdapterReact();
 ⨯ src/pages/_app.tsx (23:41) @ Component
 ⨯ unhandledRejection: TypeError: Cannot destructure property 'Component' of 'undefined' as it is undefined.
    at App (webpack-internal:///./src/pages/_app.tsx:52:22)

Any insights or suggestions on how to resolve this issue?

Answer №1

Here is the solution I found in my tsconfig.json file that resolved my issue:

{
    "compilerOptions": {
        "baseUrl": ".",
        "target": "es5",
        "lib": ["dom", "dom.iterable", "ESNext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "bundler",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "paths": {
            "@lib/*": ["src/lib/*"],
            "@css/*": ["src/css/*"],
            "@icon/*": ["src/icon/*"]
        },
        "types": ["bun-types", "web"]
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules", ".next"]
}

After experimenting with different values for module and moduleResolution, this configuration worked for me.

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

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Error message: "The toJSON method is not found for the item in the nested array of

Encountering an issue with NSwag in my Angular project where it throws an error when attempting to send data if the object contains a nested array of objects like this: export interface IJobAdDto { mainJobAd: JobAddDetailsDto; differentLanguageJobA ...

A call signature is missing in the expression type of Typescript, preventing it from being invoked

While I know there are similar questions out there, none of them have provided the answer I'm looking for. My goal is to create a straightforward function in my Angular application. In my app.component.ts file: formClick() { const formContainer ...

NextJS Link not navigating pages correctly

I have implemented a slug page directory using next.js. Here is the structure of my directory: Pages -Main --[cat] ---[content].js When I navigate to the content page using next/link from another page, it loads perfectly. However, when I try to access th ...

Error: Axios encountered an issue with resolving the address for the openapi.debank.com endpoint

After executing the ninth command to install debank-open-api, I encountered an error while running the code in my index.js file. To install debank-open-api, I used the following command: npm install debank-open-api --save Upon running the following code ...

What methods are recommended for implementing changes in a TypeScript library throughout the development process?

When working on a TypeScript library that is utilized as a dependency by other libraries or applications, how can I efficiently handle frequent updates without going through the process of incrementing the version number, publishing it to an NPM registry, ...

Removing the AM and PM from OwlDateTime in Angular is simple since the time format is already in 24-hour time

Using OwlDateTime in a 24-hour format: <div *ngIf="isSchedule" class="form-inline"> <label style='margin-right:5px ;margin-left:210px'> Date Time: <input [owlDateTimeTrigger]="dt" [owlDateTime]="dt" class="form-control" placeh ...

Tips for showing Server Action data on a webpage

Recently, I have been delving into Next.js 14 and experimenting with Server Actions to interact with the OpenAI API. My aim is to gather user input, transmit it to the OpenAI API, and then showcase the API's response on the page using pre tags. While ...

performing resolver when needed in angular version 5

I have been working on a project using Angular and recently updated it from version 4.2 to Angular 5. Although I haven't utilized any new features introduced in Angular 5 yet. My current task involves executing a resolver on a specific route when a c ...

"The ion-label in Ionic2 is cutting off some of the text and not displaying it

I'm currently facing an issue with ion-label inside ion-item. The description is not properly displaying and instead, it shows dot-dot.. ..I need the entire text to be visible. Is there any solution available? <ion-card *ngFor="let product of prod ...

Angular data binding with an object instead of an array list

Currently, I am implementing Angular and attempting to iterate through an object. Data in JSON format employee {"fName":"mike","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ebb3b3b3b3b3b3b3b3ab83849f868a8287c588848 ...

The presence of a constructor in a component disrupts the connection between React and Redux in

I am facing an issue with the connect function from 'react-redux' in my Typescript class example. The error occurs at the last line and I'm struggling to understand why it's happening. The constructor is necessary for other parts of the ...

Using createContext in React.tsx to pass the state through useState

There is a context called Transaction that accepts an object and a function as parameters. In the AppProvider component, the Transaction.Provider is returned. The following code snippet is from the GlobalState.tsx file: import { createContext, useState } f ...

The 'setState' property is not found on the 'Window' type

I am encountering an issue with the code snippet in my index.tsx file let state = {}; window.setState = (changes: any) => { state = Object.assign({}, state, changes); ReactDOM.render(<App {...state} />, document.getElementById("root")); ...

Specify the dependencies in the package.json file to ensure that the React package designed for React v17 is compatible with React v18 as well

Recently, I developed an npm package using React v17.0.2. The structure of the package.json file is as follows: { "name": "shoe-store", "version": "0.1.0", "private": true, "dependencies": ...

Guide on dynamically caching a Server Side Rendered Page in Next.js with Dynamic Routes

I am in the process of deploying a Next.js Application on AWS using ECS/Fargate because I have specific requirements that prevent me from using Amplify for custom logging and monitoring purposes. My application utilizes api-routes and dynamic-routes with S ...

What is the best way to retrieve the Hash value of an object in Typescript?

What is the process for obtaining the hash value of an object in typescript? For instance: let user:any = {name:'tempuser', age:'29'}; let anotheruser:any = {name:'iam', age:'29'}; if( Object.GetHashCode(user) === ...

Using TypeORM to establish a ManyToOne relationship with UUID data type for the keys, rather than using integers

I am currently facing a challenge in my Typescript Nestjs project using TypeORM with a PostgreSQL database. The issue arises when trying to define many-to-one relationships, as TypeORM insists on creating an ID field of type integer, while I prefer using U ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Next.js not storing prop value in state variable

In my current project using Next.js, I am facing an issue with passing props from one component to another. These props include properties of a product such as name, ID, and quantity. This particular component is a Cart Component responsible for rendering ...