Skip to content
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
@aduh95

Description

@aduh95

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 using require.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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions