Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

SyntaxError: Cannot use import statement outside a module

A .js file is CommonJS unless package.json says module. The three valid configurations, the __dirname cascade, JSON import attributes and the browser version of the same error.

~5 min readNode.js
#Node.js#ES Modules#JavaScript#Build
3D diagram of an import arrow stopped by a module wall with a dashed door opening, headline OUTSIDE A MODULE

Introduction & Quick Summary

Symptom. Node reads a file and stops on its first import line:

code
file:///app/src/index.js:1 import { readFile } from "node:fs/promises"; ^^^^^^ SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:77:18)

The same text appears in a browser console as Uncaught SyntaxError: Cannot use import statement outside a module when a <script> tag loads a file containing import without type="module". Both are the same mistake in different parsers: ESM syntax handed to a CommonJS (or classic script) parser.

Cause. In Node, the module format of a .js file is decided by the nearest package.json: "type": "module" makes .js files ESM, anything else makes them CommonJS. A .mjs file is always ESM and a .cjs file is always CommonJS. When no type field exists, import/export at the top level of a .js file is a syntax error, because CommonJS has no such statement.

Fix. Choose the format deliberately: add "type": "module" to the package and keep .cjs for the files that must stay CommonJS, or leave the package CommonJS and rename ESM files to .mjs. Converting usually exposes follow-ups — __dirname disappears, relative imports need an extension, require() of a JSON file becomes an import attribute — and those are section 4.

Core Mechanics, Signatures & Reproducible Setup

Node decides in this order: extension (.mjs → ESM, .cjs → CommonJS), then the nearest package.json type field, then the default CommonJS. Nothing else — not file contents, not import usage — changes the decision.

bash
mkdir esm-demo && cd esm-demo cat > index.js <<'JS' import os from "node:os"; console.log(os.platform()); JS node index.js # SyntaxError: Cannot use import statement outside a module node --input-type=module index.js # still fails: --input-type applies to stdin/-e only node --check index.js # same syntax error, without executing

Confirm what Node believes about the file instead of guessing:

bash
node -p "require('./package.json').type ?? '(absent -> commonjs)'" node -p "require('module').findPackageJSON ? 'has findPackageJSON (node 22.12+)' : 'older'" node --version

node --check and node -p are read-only and worth running before any edit, because the error can also come from a dependency's file loaded through a dynamic import(), where the terminal line number points at code you did not write.

The three valid configurations, with the resulting behaviour:

code
# package.json: { "type": "module" } index.js -> ESM index.cjs -> CommonJS # package.json: { "type": "commonjs" } or absent index.js -> CommonJS index.mjs -> ESM

Key Comparison Table

Setting.js.mjs.cjsrequire() of ESM
"type": "module"ESMESMCommonJSFails before Node 22.12 with ERR_REQUIRE_ESM
"type": "commonjs"CommonJSESMCommonJSERR_REQUIRE_ESM
No type fieldCommonJSESMCommonJSERR_REQUIRE_ESM
--experimental-default-type=moduleESMESMCommonJS—

What changes after switching a package to ESM:

In CommonJSIn ESM
require("./util")import "./util.js" — extension required
require("./dir") resolves dir/index.jsDirectory imports are not resolved; import "./dir/index.js"
__dirname, __filenameimport.meta.dirname, import.meta.filename (Node 20.11+)
require("./data.json")import data from "./data.json" with { type: "json" } (Node 22+)
module.exports = fnexport default fn
Free top-level await is illegalAllowed at module top level

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Adding "type": "module" and hitting __dirname is not defined

The classic cascade. Every CommonJS global written as a bare identifier now throws ReferenceError: __dirname is not defined in ES module scope. The replacement is import.meta:

js
// before (CommonJS) const path = require("node:path"); const dataFile = path.join(__dirname, "data.json"); // after (ESM) import path from "node:path"; // Node 20.11+ and 21.2+ only: const dataFile = path.join(import.meta.dirname, "data.json"); // portable fallback for older Node import { fileURLToPath } from "node:url"; const here = path.dirname(fileURLToPath(import.meta.url)); const port = path.join(here, "data.json");

import.meta.dirname is undefined before Node 20.11, which turns a working file into TypeError: The "path" argument must be of type string on an older runtime — check engines before using it.

2. Relative imports that worked before and now fail

ESM has no extension guessing. import { x } from "./lib/util" throws ERR_MODULE_NOT_FOUND, and a directory import fails too. TypeScript users see this twice, because the compiler accepts ./util under "module": "commonjs" and rejects or misemits it under NodeNext:

ts
// tsconfig.json { "compilerOptions": { "module": "nodenext", "moduleResolution": "nodenext", "target": "es2022", "verbatimModuleSyntax": true } }
ts
// source: write .js, even though the file on disk is .ts import { slugify } from "./lib/slugify.js"; import type { Post } from "./types/post.js";

Under nodenext the emitted import keeps the extension, so .js is correct in the source. Writing ./lib/slugify.ts compiles with allowImportingTsExtensions and then fails at runtime.

3. One package, two formats: the .cjs escape hatch

The cleanest migration path for a codebase with one stubborn CommonJS dependency is a per-file override rather than a per-package flag. Set "type": "module", keep the odd file as .cjs, and reference it with createRequire where you must call into CommonJS:

js
import { createRequire } from "node:module"; const require = createRequire(import.meta.url); const legacy = require("./legacy/old-tool.cjs"); // CommonJS, from an ESM file const pkg = require("./package.json"); // JSON without import attributes

createRequire is also the pragmatic way to read JSON below Node 22, where with { type: "json" } is not yet available for import.

4. Test runners keep their own opinion

Jest's default transform runs files through Babel's CommonJS transform, so a repo that works with node fails under jest with the same message. Vitest reads the package type and is usually fine. For Jest, either keep the test files in CommonJS (.cjs, .test.cjs) or point Jest at the ESM path:

js
// jest.config.mjs export default { testEnvironment: "node", transform: {}, extensionsToTreatAsEsm: [".ts"], moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1" }, };

Run it with NODE_OPTIONS=--experimental-vm-modules npx jest. The alternative — ts-jest plus a tsconfig with "module": "commonjs" — is simpler and reintroduces none of this; pick one and keep the test toolchain in the same format as production.

5. require() of an ESM-only dependency

An ESM-only package has no CommonJS entry, so require("chalk") in a CommonJS file throws ERR_REQUIRE_ESM (or Cannot use import statement outside a module if the package ships one .js flagged as ESM). Node 22.12 and 23 enable require(esm) for modules without top-level await; older runtimes need the dynamic form:

js
// works on every Node 14+ const chalk = (await import("chalk")).default; // inside an async function

Nowhere is this sharper than in a CLI: the top-level await is legal only in an ESM file, so a CommonJS entry point has to wrap the dynamic import in an async main().

6. The browser version of the error

<script src="/app.js"> parsing import fails because classic scripts are not modules. The fix is one attribute, plus the CORS and MIME rules that come with modules:

html
<script type="module" src="/app.js"></script>

Modules are deferred, always strict, and fetched with CORS semantics, so opening index.html from file:// fails with an opaque CORS error and a server returning Content-Type: text/html for a .js file fails with Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html".

Common Compilation/Runtime Mistakes & Version Gotchas

  • Setting "type": "module" without checking every .js file. CommonJS syntax (require, module.exports, __dirname) is then a ReferenceError at runtime, not a build error.
  • Forgetting the lockfile and node_modules. Some tooling caches the resolution; after changing type, reinstall before concluding the change did nothing.
  • --experimental-specifier-resolution=node. Removed in Node 19; the flag no longer restores extensionless imports, and code relying on it breaks silently on new Node majors.
  • Bare import "./config" in TypeScript with moduleResolution: bundler. It compiles, then fails under Node with ERR_MODULE_NOT_FOUND; nodenext is what catches it.
  • JSON imports without attributes. import pkg from "./package.json" needs with { type: "json" } on Node 22+ and assert { type: "json" } on 18 and 20. Missing attributes produce ERR_IMPORT_ATTRIBUTE_MISSING, not the original message.
  • __dirname in a .mjs file copied from documentation. Older guides suggest import.meta.url plus fileURLToPath; keep the fallback if engines.node allows below 20.11.
  • node --input-type=module file.js. The flag applies only to --eval and stdin, so it changes nothing for a file and wastes an afternoon.
  • Dual-package hazard. A package that ships both CJS and ESM builds can be loaded twice, producing two copies of a singleton. Use an exports map with import/require conditions and test both entry points.

Related tools. When a package.json change is in play, format both the before and after manifests with the JSON formatter and diff them with the text diff tool — a missing "type" key or a stray "exports" block is invisible in a one-line terminal output — and keep the exact node --version in the issue, since the same file behaves differently on 18, 20 and 22.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.