Node.js refuses to run a file that uses import
SyntaxError: Cannot use import statement outside a moduleShort answer
Node picks CommonJS or ES modules per file. The error means your file uses import but Node loaded it as CommonJS. Check the nearest package.json: add "type": "module", rename the file to .mjs, or switch to require. Tools that run tests or TypeScript have their own switch.
Fix it fast
1Find out which cause you have
Find which package.json Node uses for the file and what its type field says. No type field, or commonjs, means every .js file below it is CommonJS.
npm pkg get type find . -name package.json -not -path "./node_modules/*"2Match what you see, then jump to its fix
- 1
The error points at your first import line, and npm pkg get type prints {}package.json says commonjs, or has no type field on an older Node.jsFix - 2
The failing file ends in .cjs, or lives in a folder whose own package.json says commonjsThe file is .cjs, or a CommonJS package loads itFix - 3
The error appears with node -e, node --eval or a piped script, and there is no file at allCode passed to node as a string or from stdinFix - 4
ReferenceError: require is not defined in ES module scope, or __dirname is not definedAfter switching to ES modules, require and __dirname stop workingFix
- 1
What does the error look like?
SyntaxError: Cannot use import statement outside a module(node:1234) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
Cause 1 of 4
package.json says commonjs, or has no type field on an older Node.js
1Check
For a .js file, Node reads the nearest parent package.json. With type set to commonjs the file is CommonJS and a plain import statement is not allowed in it. With no type field, Node.js 22.7 and 20.19 or newer detect ES module syntax and run the file, while older versions treat it as CommonJS.
npm pkg get type2Fix
Tell Node that this package uses ES modules. Then every .js file below that package.json is read as an ES module, so any leftover require() calls in those files must change as well.
npm pkg set type=module
node server.js3Verify
The server starts and the import line no longer fails.
node server.jsConfirmed by nodejs.org
Cause 2 of 4
The file is .cjs, or a CommonJS package loads it
1Check
A .cjs file is always CommonJS, whatever package.json says. A nearer package.json can also override the one at the project root.
ls -l server.cjs
find . -name package.json -not -path "./node_modules/*"2Fix
Rename the file to .mjs to force ES module loading, or to .js inside a package whose type is module. If the file should stay CommonJS, replace import with require instead.
mv server.cjs server.mjs
# or, staying on CommonJS:
# const express = require('express');3Verify
Run the renamed file directly.
node server.mjsConfirmed by nodejs.org
Cause 3 of 4
Code passed to node as a string or from stdin
1Check
String input is not read from package.json. Without a flag it runs as CommonJS.
node -e "import fs from 'node:fs'; console.log(typeof fs.readFileSync)"2Fix
Give Node the input type explicitly.
node --input-type=module -e "import fs from 'node:fs'; console.log(typeof fs.readFileSync)"3Verify
The command prints function.
node --input-type=module -e "import fs from 'node:fs'; console.log(typeof fs.readFileSync)"Confirmed by nodejs.org
Cause 4 of 4
After switching to ES modules, require and __dirname stop working
1Check
ES modules do not define require, module.exports, __filename or __dirname. This is the usual next error once the import error is gone.
grep -rn "require(\|__dirname\|module.exports" --include=*.js src/ server.js2Fix
Use import and export, and replace __dirname with import.meta.dirname. If one CommonJS-only call remains, createRequire gives you a require.
import path from 'node:path';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const publicDir = path.join(import.meta.dirname, 'public');3Verify
Start the app again and open a route that serves a file.
node server.jsConfirmed by nodejs.org
How do I stop it coming back?
- Set the type field in package.json when you create a project, even for CommonJS, so Node never has to guess.
- Use one module style per package. Keep a rare CommonJS file as .cjs instead of mixing styles inside .js files.
- Use the file extension in relative imports (./routes/users.js); ES modules do not add it for you.
- Pin Node.js in package.json engines so every machine picks the same behaviour.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Node.js says Cannot find module when you run or require a file
Error: Cannot find module './routes/users'
Node.js looked for the name you gave it in every place its resolver knows and found nothing.
4 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fix