Importing ES module into Next.js leads to ERR_REQUIRE_ESM

Encountered this issue while attempting to integrate ky into a Next.js project:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /foo/node_modules/ky/index.js

It seems that the cause of this problem is Webpack (or Babel) converting all imports to require()s, whereas ky functions as a pure ES module.

To resolve this issue, I found a workaround by dynamically importing ky before utilizing it, although this method lacks elegance and efficiency.

const handleFormSubmit = async (event) => {
  const ky = (await import("ky")).default;

  const response = await ky
    .get('http://localhost/api/foo')
    .json();
};

Any recommendations for a better approach?

Answer №1

Starting with Next.js 12, ES Modules are now supported by default. If the ESM library has

"type": "module"
in its package.json, there is no longer a need to use next-transpile-modules for transpilation.


Prior to Next.js 12

If an ESM like ky needs to be transpiled, you can use next-transpile-modules in the next.config.js file.

// next.config.js
const withTM = require('next-transpile-modules')(['ky']);

module.exports = withTM(/* your Next.js config */);

Answer №3

After the release of Next.js 12 (official announcement), support for ESM modules has been automatically activated. More details can be found in #29878.

In the latest version, Next.js 12.1, you have the option to include

"type": "module"
in your package.json. Refer to #33637 for more information.

Answer №4

For those using NextJS 12 (and possibly 13) with TypeScript: Take a look at this resource. Make sure to include --esm in your "dev" line within your main package.json as recommended by this user's suggestion here. Additionally, ensure that your tsconfig.server.json file (inherits from tsconfig.json) specifies

"module": "ESNext"
rather than
"module": "commonjs"
.

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

What is the process for obtaining a compilation of JavaScript files that are run when an event is triggered?

How can I generate a list of all the JavaScript files that are triggered when a button is clicked or an input field is selected in a complex system? Is it possible to achieve this with Chrome DevTools, or are there alternative solutions available? If Chro ...

Incorporate JavaScript strings into HTML dynamically

I am facing some challenges with single quotes while trying to append HTML with a JavaScript string. So far, I have managed to successfully append the element: $("<a class='action-button' id='pl65197buy' value='buy now'&g ...

Developing a Node.js system for mapping ids to sockets and back again

Managing multiple socket connections in my application is proving to be a challenge. The app functions as an HTTP server that receives posts and forwards them to a socket. When clients establish a socket connection, they send a connect message with an ID: ...

The presence of an Angular Element within an Angular application can lead to a problematic cycle of constant reloading,

, I am encountering issues with integrating Angular Elements as plugins into my Angular application. The problem arises when building the element with "--prod" - it functions properly with "ng serve" in my development setup but causes infinite reloading wh ...

Combining multiple AngularJS expressions to form a URL within an interpolation statement

While this explanation may be lengthy, I appreciate your patience as I try to articulate the issue at hand. The error I'm currently encountering is as follows: Error: [$interpolate:noconcat] Error while interpolating: Strict Contextual Escaping disa ...

Utilize Vuetify to showcase a vertical layout consisting of a header and a v-card, occupying the full height

<template> <div> <div style="height: 20px; color: yellow"> test </div> <v-card class="markdown-preview" tile> <v-card-text v-html="previewText"> </v-card-text> ...

Alter the value of a parameter within a script tag with JavaScript/jQuery

Looking to dynamically change a parameter value using JavaScript or jQuery. Here is an example URL: www.exampleurl.com/somepage?foo=test I have a function that can extract the value after the 'foo' parameter: function getParameterByName(name, ...

AngularJS- numerous unique directives featured on a single page each with its distinctive state

Regarding the query about Calling a method in a directive controller from another controller. Is there a way to have multiple separate directives of the same type on a page? Since they share a common API (singleton), the state is also shared. Therefore, i ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

Tips for displaying an alpha-numeric keyboard in a React Native application

I am struggling to display an alpha-numeric keyboard in my React-Native App. I have tried various values for the keyboardType prop, but none of them seem to work for me. If anyone has any suggestions on how I can achieve this, please do share your ideas w ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...

How can I retrieve the content from an iframe whenever its state is altered using jQuery?

I am currently working on a project where I need to extract the content from a hidden iframe and display it as HTML in a div every time the iframe changes its loading state. The goal is for it to appear as if the page is being redirected and downloading it ...

What is the best way to eliminate an object from an array of objects that fulfills a specific condition?

Upon receiving an object in my function containing the information below: { "name": "Grand modèle", "description": "Par 10", "price": 0, "functional_id": "grand_modele_par_10", "quantity": 2, "amount": 0 } I must scan the next array of objec ...

What are the best strategies for creating HTML website designs that are both scalable, adaptable, and versatile?

As a beginner in HTML website design, I have recently started using HTML, CSS, jQuery, and JavaScript for designing websites. After creating a site with almost forty webpages, the client requirements are changing, requiring changes to be made across all ...

Guide on adding a personalized table or Div section in a datatable

I am looking to add a custom table above a datatable, specifically I want the custom table to be displayed above the header columns. Here is the code I have tried: columns: [ { "data": "WorkFlowType" }, { "data": "WorkflowInstanceId" } ...

Node.js client encounters ENOBUFS error due to excessive number of HTTP requests

Currently, I have the following setup: An end-to-end requests system where a node.js client communicates with a node.js server. However, the issue arises when the client fails with an ENOBUFS error in less than a minute. client: (function(){ var lo ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...