node · JavaScript
The message
ReferenceError: require is not defined in ES module scope, you can use import instead
What it means
This is the exact mirror of the previous error — the file is being read as ESM and it contains CommonJS's require. It happens almost always right after adding "type": "module" to package.json while old scripts are still in the tree. To leave that one file in the old world, mv script.js script.cjs is the narrowest change; to move it forward, rewriting require as import also means dealing with __dirname and require.main === module, which do not exist in ESM.
The fix
mv script.js script.cjs- Printed by
- node
- JavaScript
- 15
Browser and Node errors usually tell you what broke and not why the value became what it was — you read undefined, it was not a function, it was not JSON — so the place to fix is upstream of the line that threw, and silencing just that line with ?. and default values makes the same problem reappear further away in a form that is harder to recognise.
Reading an error message
- Read from the first line down. The lower you go the more it is about the tool’s internals; the cause is usually at the top.
- If there is a file and a line number, start there — not the top stack frame, but the topmost line that names a file you wrote.
- Search the message verbatim, but strip your own paths and variable names first; those are what stop the search from matching.
- The same condition is worded differently across tool versions. If results look wrong, add the version number to the query.
- Before pasting a fix, check what it throws away. Some of these cannot be undone.
Common questions
Q. What does “ReferenceError: require is not defined in ES module scope, you can use import instead” mean?
This is the exact mirror of the previous error — the file is being read as ESM and it contains CommonJS's require. It happens almost always right after adding "type": "module" to package.json while old scripts are still in the tree. To leave that one file in the old world, mv script.js script.cjs is the narrowest change; to move it forward, rewriting require as import also means dealing with __dirname and require.main === module, which do not exist in ESM.
Q. How do I fix it?
mv script.js script.cjs — before running it, check the explanation above for what this command discards.
Q. Which tool prints this?
node. It sits under JavaScript, and the message runs to 14 words.