This repository was archived by the owner on Sep 2, 2023. It is now read-only.
This repository was archived by the owner on Sep 2, 2023. It is now read-only.
import(cjs) messes with module.parent #469
Closed
Description
Some packages use a check on module.parent
to know if they are launched from CLI or required by another module:
// module.cjs
if (!module.parent) throw new Error("Running from CLI is not supported!");
This works fine if you use require
(I tried from both CJS and ES modules):
$ node -p "assert.doesNotThrow(()=>require('./module.cjs')), 'No error!';"
No error!
However, when importing from ESM, that doesn't work:
// module.mjs
import './module.cjs'; // This will throw the "don't run from CLI" Error...
console.log('This is fine.'); // This is never reached
Same for dynamic imports:
// module.js // (same behaviour on ESM and CJS)
import('./module.cjs')
.then(()=>console.log('This is fine.'))
.catch(()=>console.log('Oh no!'))
I can see three ways to tackle this issue, but none is very satisfying to me:
- Make
module.parent
truthy when a CJS is imported (although I have no idea what it could look like). - Deprecate
module.parent
? Packages usingrequire.main===module
are fine, so that's what library authors should be using to test this, right? - Disregard this issue, as users can use
module.createRequire
to workaround the issue.
Metadata
Metadata
Assignees
Labels
No labels