Skip to content
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

CJS/Native ESM incompatibilities #16

Closed
cyco130 opened this issue Sep 22, 2022 · 2 comments
Closed

CJS/Native ESM incompatibilities #16

cyco130 opened this issue Sep 22, 2022 · 2 comments
Labels
wontfix This will not be worked on

Comments

@cyco130
Copy link
Owner

cyco130 commented Sep 22, 2022

vavite templates use Node's native ESM ("type: "module") by default. This causes several incompatibility issues with some packages. This is not a vavite or vite issue. Those packages are simply incompatible with Node's native ESM and it should be fixed on their end.

The most common problem manifests itself when you try to access a named export from a CommonJS module:

import { something } from "some-cjs-package";
              ^^^^^^^^^
SyntaxError: Named export 'something' not found. The requested module 'some-cjs-package' is a CommonJS module, which may not support all module.exports as named exports.

CommonJS modules can always be imported via the default export, for example using:

import pkg from 'some-cjs-package';
const { something } = pkg;

As the error message explains, this is not supported by Node. CJS modules, when imported from Node ESM modules only provide a single default export and no named exports. The proper solution is to follow the advice at the end of the error message (or read on for a different solution).

Another solution is to switch back to CJS (read instructions). But it's a legacy feature and maybe removed at some point.

Another compatibility problem is when a package exports an ESM module with a .js extension without "type: "module" in its package.json. The package should either use "type: "module" or rename their files to .mjs.

Usually both issues can be solved by forcing Vite to process that dependency. It is achieved by adding ssr: { noExternal: ["package-name"] } to your Vite config.

@cyco130 cyco130 added the wontfix This will not be worked on label Sep 22, 2022
@cyco130
Copy link
Owner Author

cyco130 commented Sep 22, 2022

As said, this is not a vavite or vite issue so it won't be fixed.

@cyco130
Copy link
Owner Author

cyco130 commented Oct 28, 2022

This plugin can help you unwrap the default import: https://github.com/cyco130/vite-plugin-cjs-interop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
wontfix This will not be worked on
Projects
None yet
Development

No branches or pull requests

1 participant