module: disable CommonJS support if entry point is ESM
If the entry point is using ESM syntax and there's no package.json
file to determine the default "type"
, disable CJS support and try to load the file again.
This is an attempt to help newcomers get started with Node.js without forcing them to use .mjs
or have a package.json
to use ESM syntax. It should be noted that using .mjs
(or packge.json#type
) would give you much better startup performance, I wouldn't recommend anyone to use this hack on production code.
Behavior on master
:
(node:22414) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
…:1
console.log('hey it works');export{}
^^^^^^
SyntaxError: Unexpected token 'export'
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1025:15)
at Module._compile (node:internal/modules/cjs/loader:1059:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:816:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
Behavior with this PR:
(node:22430) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:22430) Warning: No package.json detected, attempting to load "…" with CommonJS support disabled.
hey it works
/cc @nodejs/modules