module: check --experimental-require-module separately from detection · nodejs/node@1db210a
@@ -1404,7 +1404,7 @@ function loadESMFromCJS(mod, filename) {
14041404 * @param {'commonjs'|undefined} format Intended format of the module.
14051405 */
14061406function wrapSafe(filename, content, cjsModuleInstance, format) {
1407-assert(format !== 'module'); // ESM should be handled in loadESMFromCJS().
1407+assert(format !== 'module', 'ESM should be handled in loadESMFromCJS()');
14081408const hostDefinedOptionId = vm_dynamic_import_default_internal;
14091409const importModuleDynamically = vm_dynamic_import_default_internal;
14101410if (patched) {
@@ -1434,7 +1434,17 @@ function wrapSafe(filename, content, cjsModuleInstance, format) {
14341434};
14351435}
143614361437-const shouldDetectModule = (format !== 'commonjs' && getOptionValue('--experimental-detect-module'));
1437+let shouldDetectModule = false;
1438+if (format !== 'commonjs') {
1439+if (cjsModuleInstance?.[kIsMainSymbol]) {
1440+// For entry points, format detection is used unless explicitly disabled.
1441+shouldDetectModule = getOptionValue('--experimental-detect-module');
1442+} else {
1443+// For modules being loaded by `require()`, if require(esm) is disabled,
1444+// don't try to reparse to detect format and just throw for ESM syntax.
1445+shouldDetectModule = getOptionValue('--experimental-require-module');
1446+}
1447+}
14381448const result = compileFunctionForCJSLoader(content, filename, false /* is_sea_main */, shouldDetectModule);
1439144914401450// Cache the source map for the module if present.
@@ -1471,8 +1481,6 @@ Module.prototype._compile = function(content, filename, format) {
14711481}
14721482}
147314831474-// TODO(joyeecheung): when the module is the entry point, consider allowing TLA.
1475-// Only modules being require()'d really need to avoid TLA.
14761484if (format === 'module') {
14771485// Pass the source into the .mjs extension handler indirectly through the cache.
14781486this[kModuleSource] = content;