-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
fix(cjs): Use module
instead of require
for CJS check
#15927
Conversation
packages/node/src/utils/commonjs.ts
Outdated
@@ -1,4 +1,4 @@ | |||
/** Detect CommonJS. */ | |||
export function isCjs(): boolean { | |||
return typeof require !== 'undefined'; | |||
return typeof module !== 'undefined' && typeof module.exports !== 'undefined'; |
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.
Why are we also checking for module.exports?
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.
Just some additional safety as there is maybe a variable named module
. But it's more unlikely that there is one that is an object with the key exports
.
size-limit report 📦
|
@@ -1,4 +1,8 @@ | |||
/** Detect CommonJS. */ | |||
export function isCjs(): boolean { | |||
return typeof require !== 'undefined'; | |||
try { |
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.
IMHO if we do the try catch, we can omit the && module
check xD as we should be safe already!
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.
suuper nit xD
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.
Good catch!
As `require` is supported in ESM as well from [Node 20.19.0](https://nodejs.org/en/blog/release/v20.19.0) onwards, the check does not work anymore. However, `module` is not available in ESM. Also mentioned in this comment: #14202 (comment) [Node: Compatibility with CommonJS](https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_interoperability_with_commonjs) [Bun: Using require](https://bun.sh/docs/runtime/modules#using-require)
As
require
is supported in ESM as well from Node 20.19.0 onwards, the check does not work anymore. However,module
is not available in ESM.Also mentioned in this comment: #14202 (comment)
Node: Compatibility with CommonJS
Bun: Using require