Skip to content

Commit 5fc10ca

Browse files
privatenumberrichardlau
authored andcommitted
module: load source maps in commonjs translator
PR-URL: #51033 Reviewed-By: Antoine du Hamel <[email protected]> Reviewed-By: Geoffrey Booth <[email protected]> Reviewed-By: Chengzhong Wu <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent b88170d commit 5fc10ca

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/internal/modules/esm/translators.js

+2
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,8 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) {
289289
// In case the source was not provided by the `load` step, we need fetch it now.
290290
source = stringify(source ?? getSource(new URL(url)).source);
291291

292+
maybeCacheSourceMap(url, source);
293+
292294
const { exportNames, module } = cjsPreparseModuleExports(filename, source);
293295
cjsCache.set(url, module);
294296
const namesWithDefault = exportNames.has('default') ?

test/es-module/test-esm-loader-hooks.mjs

+33
Original file line numberDiff line numberDiff line change
@@ -737,6 +737,39 @@ describe('Loader hooks', { concurrency: true }, () => {
737737
assert.strictEqual(signal, null);
738738
});
739739

740+
it('should support source maps in commonjs translator', async () => {
741+
const readFile = async () => {};
742+
const hook = `
743+
import { readFile } from 'node:fs/promises';
744+
export ${
745+
async function load(url, context, nextLoad) {
746+
const resolved = await nextLoad(url, context);
747+
if (context.format === 'commonjs') {
748+
resolved.source = await readFile(new URL(url));
749+
}
750+
return resolved;
751+
}
752+
}`;
753+
754+
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
755+
'--no-warnings',
756+
'--enable-source-maps',
757+
'--import',
758+
`data:text/javascript,${encodeURIComponent(`
759+
import{ register } from "node:module";
760+
register(${
761+
JSON.stringify('data:text/javascript,' + encodeURIComponent(hook))
762+
});
763+
`)}`,
764+
fixtures.path('source-map/throw-on-require.js'),
765+
]);
766+
767+
assert.strictEqual(stdout, '');
768+
assert.match(stderr, /throw-on-require\.ts:9:9/);
769+
assert.strictEqual(code, 1);
770+
assert.strictEqual(signal, null);
771+
});
772+
740773
it('should handle mixed of opt-in modules and non-opt-in ones', async () => {
741774
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
742775
'--no-warnings',

0 commit comments

Comments
 (0)