SyntaxError: Cannot use import statement outside a module
SyntaxError: Cannot use import statement outside a moduleIn one sentence: Node.js is reading your file as old-style CommonJS, so it doesn't understand the modern `import` syntax.
What it means
JavaScript has two module systems: the modern one (`import` / `export`, called ES modules) and Node's older one (`require` / `module.exports`, called CommonJS). Node decides which one a `.js` file uses from your `package.json`.
If `package.json` doesn't say `"type": "module"`, Node treats `.js` files as CommonJS, and the first `import` line throws this error.
Common causes
- Running a script directly with `node script.js` when it uses `import` and `package.json` has no `"type": "module"`.
- A test runner (often Jest) that isn't set up for ES modules or TypeScript.
- Running a `.ts` file with plain `node` instead of a TypeScript runner.
- Mixing `require` and `import` in the same project after an AI tool copied code from different examples.
How to fix it
- For your own Node scripts: add `"type": "module"` to `package.json`, or rename the file to `.mjs`.
- For TypeScript files: run them with `npx tsx script.ts` instead of `node`.
- For Jest: use a setup that supports ES modules and TypeScript, or switch to Vitest, which handles `import` out of the box.
- Pick one style per project and convert stray `require` calls to `import` (or the other way around).
Example
{
"name": "my-app",
"type": "module"
}Prompt to paste into your AI tool
Node throws 'Cannot use import statement outside a module'. Figure out whether this project should use ES modules or CommonJS, make package.json and the file extensions consistent with that, and run TypeScript files with tsx. Explain what you changed.Still stuck?
Paste your exact error and code. Get a plain-English explanation free, or the full fix for $5.
Related errors
- TypeError: Cannot read properties of undefined
- CORS error: blocked by CORS policy
- Hydration failed: server HTML didn't match the client (Next.js)
- Module not found: Can't resolve '...'
Weekly: the errors breaking vibe-coded apps and how to fix them. Free.
No spam. Unsubscribe anytime.