-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
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
feat(ssr): support commonjs in ssrTransform
#3927
Conversation
When a dependency is (1) cloned within the Vite root and (2) is listed in `optimizeDeps.exclude`, it will pass through `ssrTransform` and might be using `require` and `module.exports`, so we need to check for that and do some basic replacements. Drawbacks include: - Comments and strings containing `module.exports` or `exports` are not accounted for, so they will be rewritten. Fixes vitejs#2579
if (!ssrModule.__esModule) { | ||
Object.defineProperty(ssrModule, '__esModule', { value: true }) | ||
if (!Object.getOwnPropertyDescriptor(ssrModule, 'default')) { | ||
Object.defineProperty(ssrModule, 'default', { value: ssrModule }) |
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.
This makes a CommonJS module compatible with ESM default import.
ES modules are not affected, since ssrTransform
now injects a Object.defineProperty
call when ESM syntax is detected.
Turns out that Closing in favor of a docs PR that mentions this caveat. |
Description
When a dependency is (1) cloned within the Vite root and (2) is listed in
optimizeDeps.exclude
, it will pass throughssrTransform
and might be usingrequire
andmodule.exports
, so we need to check for that and do some basic replacements. Dependencies inssr.noExternal
are also affected.Once we know a URL isn't a module (eg: it doesn't use
import
,export
,import.meta
or dynamicimport(...)
), we can do the following replacements:require
calls with__vite_ssr_import__
module.exports
andexports
references with__vite_ssr_exports__
module.exports
assignments with__vite_ssr_exports__.default = xxx
This PR also moves
__esModule
declaration intossrTransform
so CJS modules can be made compatible with ESM import by automatically assigningexports.default = exports
withinssrModuleLoader
if it's undefined. This allowsimport foo from 'cjs'
to work as expected.Additional context
Fixes #2579
What is the purpose of this pull request?
Before submitting the PR, please make sure you do the following
fixes #123
).