Fix: Resolve dynamic require issues when using with Vitest#50
Conversation
We still have some concerns whether this will work in all situations, including CJS.
valentinpalkovic
left a comment
There was a problem hiding this comment.
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).