Skip to content

Commit

Permalink
fix(js): set compilerOptions correctly when loading .ts that targets …
Browse files Browse the repository at this point in the history
…ESM (#27862)

When we load `.ts` files and the closest `package.json` specifies
`"type": "module"`, then the file may error upon loading. This happens
because we're not setting `compilerOptions` correctly when registering
`ts-node/esm`-- in fact there is no way to pass options through this
hook.

This PR sets defaults on `TS_NODE_COMPILER_OPTIONS` such that the
`module` and `moduleResolution` are correct values for ESM. It also
works for CJS since both `module` and `moduleResolution` check the
closest `package.json` to determine the format.

## Current Behavior
<!-- This is the behavior we have today -->

## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #23228
  • Loading branch information
jaysoo authored Sep 12, 2024
1 parent 1924bc3 commit 7232b39
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/nx/src/plugins/js/utils/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ export function registerTsProject(
// Based on limited testing, it doesn't seem to matter if we register it multiple times, but just in
// case let's keep a flag to prevent it.
if (!isTsEsmLoaderRegistered) {
// We need a way to ensure that `.ts` files are treated as ESM not CJS.
// Since there is no way to pass compilerOptions like we do with the programmatic API, we should default
// the environment variable that ts-node checks.
process.env.TS_NODE_COMPILER_OPTIONS ??= JSON.stringify({
moduleResolution: 'nodenext',
module: 'nodenext',
});
const module = require('node:module');
if (module.register && packageIsInstalled('ts-node/esm')) {
const url = require('node:url');
Expand Down

0 comments on commit 7232b39

Please sign in to comment.