[Unit tests] ReferenceError: require is not defined in ES module scope
disog opened this issue · comments
Hello there. I'm doing a build of binaryen as a dependency of an npm package. Running check.py
fails because the test/unit/input/asyncify.js
cannot be run by nodejs when the nearest parent directory which contains package.json
is configured with "type": "module"
. The error message from executing it directly is:
<redacted>/binaryen/test/unit/input/asyncify.js:6
var fs = require('fs');
^
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 '<redacted>/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///<redacted>/binaryen/test/unit/input/asyncify.js:6:10
at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
at async loadESM (node:internal/process/esm_loader:28:7)
at async handleMainPromise (node:internal/modules/run_main:113:12)
The solution is either adding a package.json
with an empty configuration ({}
) to the test/unit/input
directory or changing the script extension to .cjs
.
Which node.js version are you using? I think I saw this before and it depends on the node version, but I don't remember if newer or older versions show the error.
I'm using v20.11.0
Thanks, I can't reproduce the issue though:
NODE=~/Downloads/node-v20.11.0-linux-x64/bin/node ./check.py unit
That runs all the unit tests with node 20.11, and they pass.
Which test specifically fails for you?
Just for clarity, in your test did you add a package.json
file with {"type": "module"}
in a parent folder?
No, I was trying to first see the error before seeing if that fixes it.
To make sure I verified there is no such file in the directory, nor any parent.
No, what I mean is, to reproduce this error, there should be package.json
in a parent directory with type module (which is what my project is). Sorry for the misunderstanding.
I edited the original issue comment to be a little more precise about this fact.
I see, apologies for my confusion. That was probably obvious to someone that knows more JS, unlike me 😄
I can reproduce and see the proposed fix works. Opened #6245
No worries, I'm also a JS newcomer. 😄
Thanks for your quick feedback and resolution!