Error when a CJS module is imported from ESM module dependencies
See original GitHub issueDescribe the bug
if a dependency that is an ES module imports a dependency that is a CJS module, the following error is encountered when running with the development server:
Uncaught SyntaxError: The requested module '/dependency2/index.js' does not provide an export named 'default'
Reproduction
Clone https://github.com/JBusillo/vanilla do an ‘npm i’ and ‘npm run dev’
System Info
System:
OS: Linux 5.8 Ubuntu 20.04.2 LTS (Focal Fossa)
CPU: (6) x64 Intel(R) Core(TM) i5-8400 CPU @ 2.80GHz
Memory: 22.09 GB / 31.04 GB
Container: Yes
Shell: 5.0.17 - /bin/bash
Binaries:
Node: 14.16.1 - /usr/bin/node
Yarn: 1.22.10 - /usr/local/bin/yarn
npm: 7.9.0 - /usr/local/bin/npm
Browsers:
Brave Browser: 89.1.22.71
Chrome: 89.0.4389.114
Firefox: 87.0
npmPackages:
vite: ^2.1.5 => 2.1.5
Used package manager: npm
Additional Notes
I originally encountered this issue with the module https://github.com/IBM/carbon-components-svelte. The repro provided is simpler to demonstrate.
The problem doesn’t affect the production build when using the Rollup commonjs plug-in.
One possible solution might be to do an esbuild transform within transformRequest.ts:
...
import esbuild from 'esbuild'
...
// inserted just prior to the return 'if' block
if (file.endsWith("js")) {
const r = await esbuild.transform(code, { format: "esm" })
code = r.code
}
...
This transforms all .js files, even those that are already ESM, but esbuild doesn’t modify the code in that case. Perhaps the transformation could be an option. Or, there could be another solution altogether.
This issue is possibly related to #2679, but that addresses UMD modules imported at the root level.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:19
- Comments:20 (10 by maintainers)
Top GitHub Comments
I encountered this bug as well - a dependency (Storybook, in my case) imports core-js, and core-js uses CJS internally. Looks like you can force the file through Esbuild from your Vite config - you add the file to the optimizeDeps “include” array. But that’s cumbersome if there are lots of CJS files.
There’s now an experimental option to prebundle
.svelte
files: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#prebundlesveltelibraries