Add a shim function for unbundled uses of require
#1291
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Modules in CommonJS format automatically get three variables injected into their scope:
module
,exports
, andrequire
. These allow the code to import other modules and to export things from itself. The bundler automatically rewrites uses ofmodule
andexports
to refer to the module's exports and certain uses ofrequire
to a helper function that loads the imported module.Not all uses of
require
can be converted though, and un-converted uses ofrequire
will end up in the output. This is problematic becauserequire
is only present at run-time if the output is run as a CommonJS module. Otherwiserequire
is undefined, which means esbuild's behavior is inconsistent between compile-time and run-time. Themodule
andexports
variables are objects at compile-time and run-time butrequire
is a function at compile-time and undefined at run-time. This causes code that checks fortypeof require
to have inconsistent behavior:In the above example, ideally
CommonJS detected
would always be printed since the code is being bundled with a CommonJS-aware bundler. To fix this, esbuild will now substitute references torequire
with a stub__require
function when bundling if the output format is something other than CommonJS. This should ensure thatrequire
is now consistent between compile-time and run-time. When bundled, code that uses unbundled references torequire
will now look something like this:Fixes #1202