Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: require is not defined error #47

Merged
merged 1 commit into from
Feb 28, 2022
Merged

Conversation

richardlau
Copy link
Member

The require() function is not defined in ES module scope. Loading a
JSON file via import is behind --experimental-json-modules on LTS
versions of Node.js, so use createRequire() instead.

Refs: #43

Fixes this error when there is a package.json file in the current working directory:

$ nvm run 17 .
Running node v17.6.0 (npm v8.5.1)
file:///home/rlau/sandbox/github/branch-diff/branch-diff.js:18
const pkgData = fs.existsSync(pkgFile) ? require(pkgFile) : {}
                   ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/home/rlau/sandbox/github/branch-diff/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///home/rlau/sandbox/github/branch-diff/branch-diff.js:18:20
    at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:341:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

Node.js v17.6.0

The `require()` function is not defined in ES module scope. Loading a
JSON file via `import` is behind `--experimental-json-modules` on LTS
versions of Node.js, so use `createRequire()` instead.
Copy link
Member

@rvagg rvagg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@richardlau richardlau merged commit be4ec56 into nodejs:main Feb 28, 2022
@richardlau richardlau deleted the esm branch February 28, 2022 17:45
github-actions bot pushed a commit that referenced this pull request Feb 28, 2022
### [2.0.2](v2.0.1...v2.0.2) (2022-02-28)

### Bug Fixes

* require is not defined error ([#47](#47)) ([be4ec56](be4ec56))
@github-actions
Copy link

🎉 This PR is included in version 2.0.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants