preactjs / next-plugin-preact

Next.js plugin for preact X
394 stars 9 forks source link

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

Open kevineinarsson opened 2 years ago

kevineinarsson commented 2 years ago

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?

merlindru commented 2 years ago

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

kevlened commented 2 years ago

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);