Skip to content

Commit aac23bb

Browse files
committed
esm: use import.meta.filename/dirname instead of import.meta.url
1 parent a3cd540 commit aac23bb

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

lib/internal/modules/esm/module_job.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,10 @@ const explainCommonJSGlobalLikeNotDefinedError = (e, url, hasTopLevelAwait) => {
8686
advice = 'replace require() with import';
8787
} else if (undefinedGlobal === 'module' || undefinedGlobal === 'exports') {
8888
advice = 'use export instead of module.exports/exports';
89-
} else if (undefinedGlobal === '__filename' || undefinedGlobal === '__dirname') {
90-
advice = 'use import.meta.url instead';
89+
} else if (undefinedGlobal === '__filename') {
90+
advice = 'use import.meta.filename instead';
91+
} else if (undefinedGlobal === '__dirname') {
92+
advice = 'use import.meta.dirname instead';
9193
}
9294

9395
e.message = `Cannot determine intended module format because both ${undefinedGlobal} and top-level await are present. If the code is intended to be CommonJS, wrap await in an async function. If the code is intended to be an ES module, ${advice}.`;

test/es-module/test-esm-detect-ambiguous.mjs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,4 +463,40 @@ describe('cjs & esm ambiguous syntax case', () => {
463463
strictEqual(code, 1);
464464
strictEqual(signal, null);
465465
});
466+
467+
it('should throw an ambiguous syntax error when using top-level await with __filename', async () => {
468+
const { stderr, code, signal } = await spawnPromisified(
469+
process.execPath,
470+
[
471+
'--eval',
472+
`console.log(__filename);\nawait 1;`,
473+
]
474+
);
475+
476+
match(
477+
stderr,
478+
/ReferenceError: Cannot determine intended module format because both __filename and top-level await are present\. If the code is intended to be CommonJS, wrap await in an async function\. If the code is intended to be an ES module, use import\.meta\.filename instead\./
479+
);
480+
481+
strictEqual(code, 1);
482+
strictEqual(signal, null);
483+
});
484+
485+
it('should throw an ambiguous syntax error when using top-level await with __dirname', async () => {
486+
const { stderr, code, signal } = await spawnPromisified(
487+
process.execPath,
488+
[
489+
'--eval',
490+
`console.log(__dirname);\nawait 1;`,
491+
]
492+
);
493+
494+
match(
495+
stderr,
496+
/ReferenceError: Cannot determine intended module format because both __dirname and top-level await are present\. If the code is intended to be CommonJS, wrap await in an async function\. If the code is intended to be an ES module, use import\.meta\.dirname instead\./
497+
);
498+
499+
strictEqual(code, 1);
500+
strictEqual(signal, null);
501+
});
466502
});

0 commit comments

Comments
 (0)