Skip to content

Commit

Permalink
module: fix extensionless typescript in cjs loader
Browse files Browse the repository at this point in the history
  • Loading branch information
marco-ippolito committed Jul 27, 2024
1 parent 2d1b4a8 commit 5bbe964
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
8 changes: 6 additions & 2 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -653,9 +653,13 @@ function getDefaultExtensions() {
let extensions = ObjectKeys(Module._extensions);
const tsEnabled = getOptionValue('--experimental-strip-types');
if (tsEnabled) {
// remove .ts and .cts from the default extensions
// to avoid extensionless requires .ts and .cts files.
// it behaves similarly to how .mjs is handled when --experimental-require-module
// is enabled.
extensions = ArrayPrototypeFilter(extensions, (ext) =>
ext !== '.ts' || Module._extensions['.ts'] !== loadTS ||
ext !== '.cts' || Module._extensions['.ts'] !== loadCTS,
(ext !== '.ts' || Module._extensions['.ts'] !== loadTS) &&
(ext !== '.cts' || Module._extensions['.ts'] !== loadCTS),
);
}

Expand Down
16 changes: 6 additions & 10 deletions test/es-module/test-typescript-commonjs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ test('require a .ts file with explicit extension succeeds', async () => {
strictEqual(result.code, 0);
});

// TODO(marco-ippolito) This test should fail because extensionless require
// but it's behaving like a .js file
test('eval require a .ts file with implicit extension fails', async () => {
const result = await spawnPromisified(process.execPath, [
'--experimental-strip-types',
Expand All @@ -30,23 +28,21 @@ test('eval require a .ts file with implicit extension fails', async () => {
cwd: fixtures.path('typescript/ts'),
});

strictEqual(result.stderr, '');
match(result.stdout, /Hello, TypeScript!/);
strictEqual(result.code, 0);
strictEqual(result.stdout, '');
match(result.stderr, /Error: Cannot find module/);
strictEqual(result.code, 1);
});

// TODO(marco-ippolito) This test should fail because extensionless require
// but it's behaving like a .js file
test('require a .ts file with implicit extension fails', async () => {
const result = await spawnPromisified(process.execPath, [
'--experimental-strip-types',
'--no-warnings',
fixtures.path('typescript/cts/test-extensionless-require.ts'),
]);

strictEqual(result.stderr, '');
match(result.stdout, /Hello, TypeScript!/);
strictEqual(result.code, 0);
strictEqual(result.stdout, '');
match(result.stderr, /Error: Cannot find module/);
strictEqual(result.code, 1);
});

test('expect failure of an .mts file with CommonJS syntax', async () => {
Expand Down

0 comments on commit 5bbe964

Please sign in to comment.