Error Reference › JavaScript
JavaScript

Cannot use import statement outside a module

You used ES module import in a context that isn't treated as a module.

What it looks like

(node:1234) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module

What does "Cannot use import statement outside a module" mean?

Thrown by Node.js when a .js file using import is treated as CommonJS, and by browsers when a script with import is loaded without type="module". The same code works once the runtime knows the file is an ES module.

What causes "Cannot use import statement outside a module"?

  • A Node file without "type": "module" or .mjs.
  • A script tag without type="module".
  • A bundler/transpiler not configured.

How do I confirm the cause?

  1. In Node, check the nearest package.json for "type": "module" and the file’s extension (.mjs is always ESM, .cjs never).
  2. In a browser, check the script tag has type="module".
  3. For tests or tooling (Jest, ts-node), check the tool’s own ESM or transform settings — they often need separate configuration.

How do I fix "Cannot use import statement outside a module"?

  • Add "type": "module" to package.json (or use .mjs).
  • Add type="module" to the script tag.
  • Or use require() / configure your bundler.

How do I stop it happening again?

  • Choose ESM or CommonJS per project and declare it in package.json from the start.
  • Keep test runners and build tools configured for the same module system as the app.
Got a different error? Paste it into the Explain This Error tool → Identifies the family and the fix — runs locally, nothing uploaded.

Related errors