Troubleshooting a NextJs/TS problem with importing ESM modules

Click here for the Code Sandbox

I'm currently in the process of transitioning some code to NextJS 11 / Webpack 5, including certain modules that now exclusively support ECMAScript Modules (esm).

Prior to the upgrade, I could easily export all files as a summary in an index.ts within the folder like so:

export { default as MarkdownRenderer } from './markdownRenderer'

And in the parent folder "lib" (assuming the above is located in a directory named elements):

export * from './elements'

This method used to work for importing in my code:

import { MarkdownRenderer } from '../lib'

However, this no longer functions and results in the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. 

After experimenting, I discovered that I can't import/export the element summary index anymore - I have to directly add all components/files into the lib index as follows:

// Does not work
//export * from './elements'

// Works
export { default as MarkdownRenderer } from './elements/markdownRenderer'

I've enabled the esm flag for NextJS and even tried using next-transpile-modules, but with no success.

In the sandbox provided, take a look at the src/lib/index.ts file and toggle between the comments to see if it works or not.

How can I maintain the ability to manage my summary files on a per-folder basis? I suspect this may be a webpack issue, although I'm not entirely certain. Typescript doesn't seem to raise any issues regardless of the approach during development.

It appears to function with older versions of Node (possibly the default on CodeSandBox was Node 10), but on versions 14/16, it fails to work.

Answer №1

One way to solve this issue is by making changes to the NextJS webpack configuration:

config.optimization.providedExports = true

Solution graciously shared by the creator of webpack.

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

Using Javascript or ES6, you can compare a nested array object with another array of elements and generate a new array based on

I am dealing with a complicated array structure as shown below sectionInfo = [{id: 1, name:'ma'}, {id: 2, name:'na'}, {id: 3, name:'ra'}, {id: 4, name:'ka'}, {id: 5, name:'pa'}]; abc = [{id:'1' ...

A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular. The error message I'm encountering is: Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl' ...

Tips for setting up a listener for when the month changes in an ion-datetime object

When the user selects a different month, I need to update the highlightedDates by calling a query to retrieve all the dates of that specific month. This currently works if the user manually chooses a month and year using the top button, but not when they c ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

How to Retrieve Inputs from Child Component Form without Prop Passing?

Within the Parent component below, there is a Dropdown menu with two options. Selecting "TOP LEVEL" will display Form1, while selecting "MAKE ITEM" will show Form2. If no option is selected, both forms remain hidden. The Parent component also contains a Bu ...

Enhancing performance with NextJS 13 memoization for fetch requests

I've been tinkering with a React project using NextJS 13 and I'm facing some issues when it comes to utilizing request memoization for fetch. The problem lies in the fact that even within the same request, it still sends multiple requests to the ...

Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

There is an implicit 'any' type error binding element 'currency' in Graphql React Typescript

I am facing an issue with my code. I want to use the EXCHANGE_RATES in renderedExchangeRates, but I am receiving an error message saying "Error Message: Binding element 'currency' implicitly has an 'any' type." I understand that this is ...

Personalized Carousel using Ng-Bootstrap, showcasing image and description data fields

I have been working on customizing an Angular Bootstrap Carousel and have managed to successfully change the layout. I now have two columns - with the image on the right and text along with custom arrows on the left. My goal is twofold: First, I am lookin ...

Developing a dynamic web application using Asp.Net Core integrated with React and material

After setting up an Asp.Net Core project using the react template, I decided to incorporate material-ui by following the steps outlined on this page. However, encountered some dependency issues along the way. To resolve them, I had to update the react and ...

Having trouble retrieving data in Next.js and passing it to client components. It's just not functioning as expected

After asynchronously fetching data, I am passing it to a client component as props. However, the state of the client component is not being properly set and displayed. The props are passing correctly, but the state seems to not update for some reason. Ser ...

Dealing with situations where an Angular component's route lacks a resolver

I have a component that handles both creating new items and updating existing ones. I have set up a Resolver for the 'edit/:id' route, but have not used one for the 'new' route. ngOnInit() { if (!(this.route.snapshot.url[0].path ...

What is the best way to centralize JSDoc typedef information for easy sharing between different projects?

Currently, I am incorporating @typedef JSDoc comments at the beginning of my Javascript files to define types (primarily to access certain benefits of TypeScript without fully diving into it right now). I'm curious, where can I keep JSDoc typedef inf ...

Uncertain about the distinction between reducers and dispatchers when it comes to handling actions

I'm feeling a bit confused regarding reducers and dispatchers. While both receive actions as parameters, it doesn't necessarily mean that the actions I use in my dispatchers are the same as those used in my reducers, correct? For example, if I h ...

Modify capital letters to dashed format in the ToJSON method in Nest JS

I am working with a method that looks like this: @Entity() export class Picklist extends BaseD2CEntity { @ApiHideProperty() @PrimaryGeneratedColumn() id: number; @Column({ name: 'picklist_name' }) @IsString() @ApiProperty({ type: Str ...

The activation of [routerLinkActive] triggers an error related to the data.split function

In my lazy loaded module, I have implemented simple routing as shown below: <div id="nav"> <div class="nav-content"> <div class="nav-item" [routerLink]="'basic'" [routerLinkActive]="active-nav"> <span ...

What is preventing me from setting my Footer component to be 100% page width in Next.js?

Hey guys, I'm facing a frustrating issue where I'm trying to make my Footer component span 100% width of the page. The problem is that it's being overridden by the layoutContainer class, where I've defined some grid layout rules. If I r ...

"Render did not yield any results" - The triumvirate of NextJS, Apollo, and Jest

I am currently setting up Jest testing for NextJS pages wrapped with Apollo Client HOC wrapper. However, I am encountering an error with my current configuration: https://i.sstatic.net/r4pUm.png There seems to be confusion on how to properly configure Je ...

What is the reason for the inability of `Array<Value>, Value` to properly retrieve the type of the array value?

I am encountering an issue with the type declaration below: function eachr<Subject extends Array<Value>, Value>( subject: Subject, callback: ( this: Subject, value: Value, key: number, subject: Subject ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...