SyntaxError: Cannot use import statement outside a module - 10 Causes and Fixes
SyntaxError: Cannot use import statement outside a module means the JavaScript runtime encountered an import declaration in a file it is treating as a CommonJS script, not an ES module. The runtime refuses to parse import syntax in script mode because modules and scripts have different parsing goals and scoping rules.
This guide covers the 10 most common causes — from a missing "type": "module" in package.json to misconfigured test runners — with a reproduction and fix for each. If your case doesn't match any single cause, use the diagnostic checklist to narrow it down.
| Error | SyntaxError: Cannot use import statement outside a module |
|---|---|
| Where it happens | JavaScript — Node.js (v12+), browser tags, and build tools (Jest, ts-node, Webpack, Vitest). Also surfaces in TypeScript projects via ts-node or tsx. |
| What it means | The file uses import syntax, but the runtime is parsing it as a CommonJS script instead of an ES module. |
The Fast Fix
In most cases, you need to tell Node.js that your files are ES modules. Add "type": "module" to your package.json:
{
"name": "my-project",
"type": "module"
}
Then re-run your script. If you cannot change the module type for the whole project, rename the single file from .js to .mjs. Node.js always treats .mjs files as ES modules regardless of package.json.