Skip to content

Add fallback value for require.extensions #430

@auvred

Description

@auvred

// eslint-disable-next-line sonarjs/deprecation
export const EXTENSIONS = ['.ts', '.tsx', ...Object.keys(cjsRequire.extensions)]

Node.js docs (https://nodejs.org/docs/latest/api/modules.html#requireextensions) say that require.extensions is deprecated and

Avoid using require.extensions. Use could cause subtle bugs and resolving the extensions gets slower with each registered extension.

And indeed, when the CJS build of @pkgr/core is loaded using the ESM loader (when registerHooks.load is used), require.extensions is undefined, so Object.keys(cjsRequire.extensions) throws TypeError: Cannot convert undefined or null to object.

Reproduction:

// index.mjs
import { registerHooks } from 'node:module'

registerHooks({
  load(url, context, nextLoad) {
    return nextLoad(url, context)
  }
})

import('./cjs-package.cjs')

// cjs-package.cjs
require("@pkgr/core")

To reproduce it locally use:

mkdir repro
cd repro
echo '{"dependencies":{"@pkgr/core":"0.3.5"}}' > package.json
echo 'require("@pkgr/core")' > cjs-package.cjs
cat <<EOF > index.mjs
import { registerHooks } from 'node:module'

registerHooks({
  load(url, context, nextLoad) {
    return nextLoad(url, context)
  }
})

import('./cjs-package.cjs')
EOF
npm install
node index.mjs

I propose replacing Object.keys(cjsRequire.extensions) with something like

cjsRequire.extensions == null ? ['.js', '.json', '.node'] : Object.keys(cjsRequire.extensions)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions