import(cjs) messes with module.parent
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.parenttruthy when a CJS is imported (although I have no idea what it could look like). - Deprecate
module.parent? Packages usingrequire.main===moduleare fine, so that's what library authors should be using to test this, right? - Disregard this issue, as users can use
module.createRequireto workaround the issue.