ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
See original GitHub issueWhat version of Next.js are you using?
12.0.7
What version of Node.js are you using?
14.18.1
What browser are you using?
N/A
What operating system are you using?
macOS, Alpine
How are you deploying your application?
next start
Describe the Bug
A module which imports an es module and throws an exception at the top level has the exception swallowed and a different (vastly less helpful) exception thrown instead. I am pretty confident that this is a webpack bug, but since next vendors webpack, I’m reporting here.
Expected Behavior
When a module throws an exception during initialization, the exception should be passed to the nearest user exception handler, or crash the application. Instead, a different exception is being thrown due to webpack-generated code.
To Reproduce
Create a file lib/test.ts
like the following; require it from any page (I used an API page, may be relevant); request that page.
import { z } from "zod";
throw new Error("error");
export default { z };
You will see the following error in the console, without any stack trace:
error - ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
Things to note:
- “zod” could be replaced by any esmodule package. The root cause is that the code generated by webpack uses a dynamic
import
to import the code, causing to to be an async module. - Exporting
{ z }
is just so that the import doesn’t get tree-shaken-away.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:12
- Comments:15 (2 by maintainers)
Top GitHub Comments
Seems like this problem is connected to
esmExternals
experimental feature, which is enabled by default.I have this problem on 12.0.7 without any underlying error, just having ESM module imported in the project. Turning off experimental feature fixed the issue.
I am facing the same issue in v12.0.9 but in my case surprisingly,
next dev
works and also deploy on Vercel platform works but somehow the local build usingnext build
fails