Levi Gans
1SyntaxError: Cannot use import statement outside a moduleYou add one import line to a file that ran fine yesterday, and now nothing runs at all. No stack trace into your code, just a caret under the word import.
“Cannot use import statement outside a module” means the runtime loaded your file as an old-style script, not as an ES module. In a script, import isn’t valid syntax, so the parser stops at the first line. The fix is almost never in the code. It’s in how the file gets loaded: a package.json field, a file extension, a <script> attribute or a test runner setting.
This guide shows how each runtime decides, and the fix for Node.js, the browser, Jest and TypeScript.
What “Cannot use import statement outside a module” means
JavaScript has two module systems. CommonJS uses require() and module.exports. ES modules use import and export. A browser <script> without type="module" is a classic script, which works like CommonJS here: no import allowed.
The runtime has to pick one before it parses the file. If it picks CommonJS or a classic script and the file starts with import, you get this error. MDN puts it plainly: it happens “more often because the current file is not treated as a module.”
It’s a SyntaxError, so none of the file runs. Not the lines above the import, not the lines below.
The wording depends on the engine. This is what each one gave us for the same <script> tag:
1Chromium, Node.js: SyntaxError: Cannot use import statement outside a module2Firefox: SyntaxError: import declarations may only appear at top level of a module3Safari: SyntaxError: Unexpected token '{'. import call expects one or two arguments.
Search your logs for all three. They’re the same mistake.
How Node.js decides what a file is
Node.js 24 looks at the file extension first, then the nearest package.json.
| File | Nearest package.json | Node 24 loads it as |
|---|---|---|
.mjs | Anything | ES module |
.cjs | Anything | CommonJS |
.js | "type": "module" | ES module |
.js | "type": "commonjs" | CommonJS |
.js | No type field | Guesses from syntax |
Sources: the Node.js 24 docs on determining module system and our own runs.
The last row is the one that changed. Since Node.js 22.7.0 and 20.19.0, syntax detection is on by default. For a .js file with no type field, Node “tries to run such ‘ambiguous’ files as CommonJS first, and will retry evaluating them as ES modules” if it finds import, export, import.meta or top-level await.
So on Node 24, a .js file with import and no type field just runs. When package.json exists but has no type, Node prints a warning and still runs it:
1[MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///.../a.js is not specified and it doesn't parse as CommonJS.2Reparsing as ES module because module syntax was detected. This incurs a performance overhead.3To eliminate this warning, add "type": "module" to /.../package.json.
That means you get the error on Node 24 only when something says CommonJS out loud: a .cjs extension, "type": "commonjs", or the --no-experimental-detect-module flag. On Node 18 or older Node 20 releases there’s no detection, so any .js file without "type": "module" fails.
Here’s the part that bites. npm init -y with npm 11.19.0, the npm that ships with Node 24.21.0, writes "type": "commonjs" into the new package.json. Make a fresh project, write import in index.js, and you get the error even on the newest Node.
Fix “cannot use import statement outside a module” in Node.js
Pick one module system for the package and say it explicitly.
Use ES modules for the whole package. Set the type field. Every .js file in the package becomes an ES module.
1{2 "type": "module"3}
Use ES modules for one file. Rename it to .mjs. Node always loads .mjs as an ES module, whatever package.json says.
Stay on CommonJS. Rewrite the imports as require():
1const { readFileSync } = require("node:fs");Switching to "type": "module" changes more than imports. ES modules have no require, module.exports, __dirname or __filename. Node 24 gives you import.meta.dirname and import.meta.filename instead, and createRequire when you still need require():
1import { createRequire } from "node:module";23const require = createRequire(import.meta.url);4const config = require("./config.json");
A .cjs file stays CommonJS inside a "type": "module" package, so config files for tools that expect require() can keep working under that extension.
The opposite error: require is not defined in ES module scope
Flip the mistake around and you get its twin. Use require() in a file Node loaded as an ES module:
1ReferenceError: require is not defined in ES module scope, you can use import instead2This file is being treated as an ES module because it has a '.js' file extension and '/.../package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
Node 24 tells you exactly why, which is nice. The fixes mirror the ones above: change the require() to import, rename the file to .cjs, or build a require with createRequire.
Syntax detection causes a version of this too. A typeless .js file that mixes import and require() fails as CommonJS because of the import, gets reparsed as an ES module, and then fails on the require(). You see the warning followed by the ReferenceError. One file, one module system.
Fix it in the browser
A plain <script> is a classic script. Add type="module":
1<script type="module" src="/app.js"></script>The same applies to inline scripts. Without the attribute, Chrome, Firefox and Safari all threw the errors shown earlier. With it, the import loaded and the code ran in all three.
Two things catch people after that.
Opening the page from disk. Module scripts load through CORS. Open index.html as a file:// URL and Chrome blocks the import: “Cross origin requests are only supported for protocol schemes: chrome, chrome-untrusted, data, http, https.” Serve the folder over HTTP, even a local dev server is enough.
Scripts from another origin. MDN notes that “module scripts require the use of the CORS protocol for cross-origin fetching.” This also matters for error reporting. When a classic script from a CDN fails to parse, the page’s error handler only sees Script error. in all three browsers. With crossorigin on the tag and an Access-Control-Allow-Origin header on the response, the handler gets the real message.
In a browser, require doesn’t exist at all. A module script that calls it throws ReferenceError: require is not defined in Chrome and Firefox, and Can't find variable: require in Safari. Use import, or let your bundler handle it.
Fix “jest cannot use import statement outside a module”
Jest runs your tests as CommonJS by default. It uses Babel to turn your own import statements into require() calls, and by default it skips node_modules. The transformIgnorePatterns default is ["/node_modules/", "\\.pnp\\.[^\\\/]+$"].
So the error usually means one of two things. Either Babel isn’t set up for your own files, or a dependency ships ES modules that Jest won’t touch.
The message depends on the Jest version. Jest 29.7.0 gave us the classic one:
1Jest encountered an unexpected token2...3SyntaxError: Cannot use import statement outside a module
Jest 30.5.2 gave a different message for the same setup, with the fixes in it:
1Must use import to load ES Module: /.../node_modules/esm-dep/index.js23The file contains ESM syntax (import/export) that could not be executed as CommonJS.
Your own test files fail. Add a Babel config that compiles ES modules for Node:
1{2 "presets": [["@babel/preset-env", { "targets": { "node": "current" } }]]3}
Save it as babel.config.json and install @babel/preset-env. Both Jest versions picked it up.
A dependency fails. The stack points into node_modules. Tell Jest to transform that package too:
1// jest.config.js2module.exports = {3 transformIgnorePatterns: ["/node_modules/(?!(esm-dep|other-esm-dep)/)"],4};
Replace esm-dep with the package names from the error. The pattern means “ignore everything in node_modules except these.”
Run Jest in ESM mode instead. Jest’s ECMAScript Modules page describes this, and still calls it experimental. Start Node with --experimental-vm-modules:
1NODE_OPTIONS="--experimental-vm-modules" npx jestJest’s docs say that on Node 24.9 and later it can require() an ES module natively. In our run with Jest 30.5.2 on Node 24.21.0, that only worked with --experimental-vm-modules set. Without it, the same test failed with the message above. With it, the test passed and Node printed an ExperimentalWarning for VM Modules.
TypeScript, ts-node and tsx
TypeScript adds a trap. You write import in every .ts file, but what runs depends on how the code gets compiled or loaded.
Node 24 can run .ts files directly. Type stripping has been on by default since Node 23.6.0 and stable since 24.12.0. It follows the same rules as .js: “To use import and export syntax, add "type": "module" to the nearest parent package.json.” Node also won’t convert one module system to the other. In our run, node a.ts worked with no type field and with "type": "module", and threw this error with "type": "commonjs". A .mts file ran either way.
If you compile with tsc first, run the compiled .js file, not the source. MDN calls out this exact mistake. And check that the module setting in tsconfig.json emits the same module system your package.json declares.
ts-node is where we’d change tools. Its last release, 10.9.2, came out on December 8, 2023. With TypeScript 7.0.2 installed, it crashed before running anything: TypeError: Cannot read properties of undefined (reading 'fileExists'). It ran with TypeScript 5.9.3. tsx 4.23.15 ran the same file under "type": "commonjs", "type": "module" and no type field. For new scripts, node file.ts or tsx is simpler.
Importing an ESM-only package from CommonJS
This used to be its own headache. A CommonJS file that called require() on an ESM-only package got ERR_REQUIRE_ESM, and the usual way out was await import().
Node 24 changed that. Loading ES modules with require() works without a flag since Node 22.12.0 and 20.19.0, and stopped being experimental in 24.15.0. In our run, require() on a "type": "module" package returned its exports.
There’s one exception. If the package uses top-level await anywhere in its import graph, require() fails:
1Error [ERR_REQUIRE_ASYNC_MODULE]: require() cannot be used on an ESM graph with top-level await. Use import() instead.Use await import("package-name") for those. Dynamic import() works in CommonJS files too.
Where Interfere fits
Interfere is an error tracker for web apps that sorts each problem by how many users it affects, shows which customer accounts and customer tiers it hits, investigates the likely cause, and hands it to your coding agent over MCP.
Tools like ours were built for teams that shipped a few times a week and read every diff. Coding agents now push hundreds of pull requests to production a day. Nobody reads them all, so production is where you find out. Interfere does the first pass: it groups the errors, works out who each problem hurts, investigates the cause and hands the fix to an agent. It’s how we keep our sanity shipping this way.
This particular error mostly breaks node, Jest or your build, so you see it in a terminal or CI log. That’s the right place to catch it. The browser is the exception. A <script> that loses type="module" in a template change throws for every visitor of that page, and it can be quiet: six checkout visitors a day, under a harmless error firing 40,000 times. Interfere groups the occurrences into one problem and ranks it by affected users, so the quiet one gets its own row.
The Inbox shows which customer tiers each problem reaches, using tiers you set through our API, and Companies names the accounts. Four users on Enterprise can matter more than four hundred on Free, and you set the priority to match. We think that’s a better way to decide what to fix than counting events.
Each problem comes with traces, logs and a session replay that starts up to seven seconds before the error. The investigation ties the likely cause to a release and the code. When it can show the cause in code, it suggests a fix, and your coding agent picks it up over MCP. Interfere never opens pull requests itself.
It’s for web apps, with SDKs for Next.js, React with Vite and TanStack Start, and no mobile SDKs. Related: Failed to fetch dynamically imported module, how to prioritize bugs by user impact. Set up Interfere.
The short version
The file is fine. The loader picked the wrong module system. In Node, set "type": "module" or use .mjs, and watch for the "type": "commonjs" that npm init now writes. In the browser, add type="module" and serve over HTTP. In Jest, configure Babel or let transformIgnorePatterns through the package named in the error. Then pick one module system per file, and both this error and its require twin go away.




