-
Notifications
You must be signed in to change notification settings - Fork 11
Fix: Resolve dynamic require issues when using with Vitest #50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
We still have some concerns whether this will work in all situations, including CJS.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code looks good. Please verify whether it is working! :)
…ger causes a dynamic require error with vitest
Upon further investigation, I discovered that this error occurs when "type": "module" is specified in the package.json of the package running Vitest. You can confirm the behavior before and after this pull request by running test:storybook in the example directory of the following branches. The first link shows the error occurring before the fix, and the second link shows the error resolved by this PR. Before fix (error occurs): https://github.com/elecdeer/vite-plugin-storybook-nextjs/tree/test/before_%2350_error_dynamic_require After fix (no error): https://github.com/elecdeer/vite-plugin-storybook-nextjs/tree/test/after_%2350_ok_no_error Would this be sufficient for you to verify the fix? |
@ghengeveld @valentinpalkovic |
Fixes #45 (comment)
Problem
This package is built with esbuild (via tsup), but esbuild converts dynamic
require()
calls into code that causes runtime errors when targeting ESM. As a result, when Vitest loads this module in ESM mode, the following error occurs:This is a known limitation of esbuild when outputting ESM code.
Reference: evanw/esbuild#1921
Solution
Replaced dynamic
require()
calls with dynamicimport()
statements to properly handle module loading in ESM environments. Dynamicimport()
works in both ESM and CommonJS environments, making this change backwards compatible.With this fix, we can now run Vitest without errors in our repository (Next.js 15.3.4).