Add flag to emit createRequire matching TS nodenext behavior #728
+89
−1
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.
Progress toward #726
This is currently an opt-in flag handling a nuance in how TS transpiles imports
like these:
In the new nodenext mode when targeting ESM, TS now transforms this code to use
createRequire
. The change is described here:https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#commonjs-interoperability
This PR adds a flag
injectCreateRequireForImportRequire
to enable thisdifferent behavior. I'm gating this behind a flag out of caution, though it's
worth noting that TS gives an error when using this syntax and targeting
module esnext, so it will likely be safe to switch to this new emit strategy as
the default behavior in the future.
As I understand it, the main benefit of this change over explicit
createRequire
is that it allows a single codebase to be transpiled to Node ESM and Node CJS
while using this syntax. A downside is that
createRequire
is Node-specific andneeds special support from bundlers, but it looks like webpack can recognize the
pattern. In most situations, real ESM
import
syntax is probably preferable,but this syntax makes it possible to force the use of CJS.
The ts-node transpiler plugin system expects transpilers to have this mode as an
option, so this is a step closer to having a compliant ts-node plugin.