esm: do not call `getSource` when format is `commonjs` · nodejs/node@bd58870 · GitHub
Skip to content

Commit bd58870

Browse files
fasttimeRafaelGSS
authored andcommitted
esm: do not call getSource when format is commonjs
Ensure that `defaultLoad` does not uselessly access the file system to get the source of modules that are known to be in CommonJS format. This allows CommonJS imports to resolve in the current phase of the event loop. Refs: eslint/eslint#17683 PR-URL: #50465 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 087cffc commit bd58870

6 files changed

Lines changed: 69 additions & 9 deletions

File tree

lib/internal/modules/esm/load.js

Lines changed: 10 additions & 9 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const fixtures = require('../common/fixtures');
5+
const assert = require('node:assert');
6+
7+
(async () => {
8+
9+
// Make sure that the CommonJS module lexer has been initialized.
10+
// See https://github.com/nodejs/node/blob/v21.1.0/lib/internal/modules/esm/translators.js#L61-L81.
11+
await import(fixtures.fileURL('empty.js'));
12+
13+
let tickDuringCJSImport = false;
14+
process.nextTick(() => { tickDuringCJSImport = true; });
15+
await import(fixtures.fileURL('empty.cjs'));
16+
17+
assert(!tickDuringCJSImport);
18+
19+
})().then(common.mustCall());
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import '../common/index.mjs';
2+
import fixtures from '../common/fixtures.js';
3+
import assert from 'node:assert';
4+
5+
let tickDuringCJSImport = false;
6+
process.nextTick(() => { tickDuringCJSImport = true; });
7+
await import(fixtures.fileURL('empty.cjs'));
8+
9+
assert(!tickDuringCJSImport);
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Flags: --experimental-loader ./test/fixtures/es-module-loaders/preset-cjs-source.mjs
2+
import '../common/index.mjs';
3+
import * as fixtures from '../common/fixtures.mjs';
4+
import assert from 'assert';
5+
6+
const { default: existingFileSource } = await import(fixtures.fileURL('es-modules', 'cjs-file.cjs'));
7+
const { default: noSuchFileSource } = await import(new URL('./no-such-file.cjs', import.meta.url));
8+
9+
assert.strictEqual(existingFileSource, 'no .cjs file was read to get this source');
10+
assert.strictEqual(noSuchFileSource, 'no .cjs file was read to get this source');

test/fixtures/empty.cjs

Whitespace-only changes.
Lines changed: 21 additions & 0 deletions

0 commit comments

Comments
 (0)