Skip to content

/errors/nodejs/cannot-use-import-statement-outside-a-module

SyntaxError: Cannot use import statement outside a module

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · v24.20.0updated
tool
Node.js
exit code
1
versions
Node.js 12+, syntax detection: Node.js 22.7+
os
any

SyntaxError: Cannot use import statement outside a module means Node.js loaded the file as CommonJS, where import declarations are not allowed. Node decides the module system per file: .mjs is always ESM, .cjs is always CommonJS, and .js follows the nearest package.json "type" field. Set "type": "module", rename the file to .mjs, or switch the code to require().

Reproduce it

bash
echo '{ "type": "commonjs" }' > package.json
echo 'import { sep } from "node:path"; console.log("separator", sep.length);' > app.js
node app.js 2>&1 | grep -v '^    at ' | sed -E 's/\(node:[0-9]+\)/(node:<pid>)/; s/\\\\\?\\//g'

Output

(node:<pid>) Warning: Failed to load the ES module: /tmp/work/app.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/tmp/work/app.js:1
import { sep } from "node:path"; console.log("separator", sep.length);
^^^^^^

SyntaxError: Cannot use import statement outside a module

Node.js v24.20.0

The stack lines (at ...) are filtered here, and the process ID in the warning is replaced. Node.js first warns that it failed to load an ES module, then shows the file, the offending line and the error.

Fix: tell Node the file is ESM

bash
echo 'import { sep } from "node:path"; console.log("separator", sep.length);' > app.js
cp app.js app.mjs
echo '{ "type": "commonjs" }' > package.json
node app.mjs
echo '{ "type": "module" }' > package.json
node app.js

Output

separator 1
separator 1

What about files without "type"?

Since Node.js 22.7, a .js file with no "type" in its package.json is first parsed as CommonJS and, if that fails because of ES module syntax, re-parsed as ESM (syntax detection). The error then only appears when "type": "commonjs" is explicit, for .cjs files, or in tools that do their own loading:

bash
echo '{ "name": "demo" }' > package.json
echo 'import { sep } from "node:path"; console.log("separator", sep.length);' > app.js
node app.js 2>&1 | sed -E 's/\(node:[0-9]+\)/(node:<pid>)/; s/\\\\\?\\//g'

Output

(node:<pid>) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///tmp/work/app.js is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to /tmp/work/package.json.
(Use `node --trace-warnings ...` to show where the warning was created)
separator 1

Sources