next-plugin-preact icon indicating copy to clipboard operation
next-plugin-preact copied to clipboard

ESM imports in Next.js >= 12 break page rendering (hooks etc.)

Open kevineinarsson opened this issue 3 years ago • 2 comments

Using an external import (react-hook-form is where I noticed the issue) which has a module export which internally uses imports from React leads to preact/compat to be re-imported as ESM. Since this is a completely separate import, errors such as not being able to use hooks occur.

This issue is not observed in vanilla React because it only contains a CJS export (afaik).

Setting experimental.esmExternals: false leads to the external being imported as CJS which leads to the same version of React as the base page being used, fixing the observed issues.

This of course won't work if a package only has a module export.


Should next-plugin-preact suggest experimental.esmExternals: false in next.config.js? Can we somehow tell webpack to always resolve imports from "react" to use CJS?

kevineinarsson avatar Jan 21 '22 17:01 kevineinarsson

Upgrading from Next.js 12.0.8 to 12.1.0 broke Next for me.

Settings experimental.esmExternals to false fixed it for me. Thanks!

Getting this resolved would let us go back to ESM imports. CJS only for now

merlinaudio avatar Mar 09 '22 00:03 merlinaudio

Here's a quick repro:

  1. With React (working): https://codesandbox.io/s/nextjs-swr-react-zh87g4
  2. With Preact (failing): https://codesandbox.io/s/nextjs-swr-preact-oz7ck8

The workaround works for me locally. Here's the resulting next.config.js:

const withPreact = require('next-plugin-preact');

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  experimental: {
    esmExternals: false
  }
}

module.exports = withPreact(nextConfig);

kevlened avatar Mar 22 '22 19:03 kevlened