SyntaxError import 🟩 Node.js

SyntaxError: Cannot use import statement outside a module

An import statement ran in a context treated as CommonJS (Node without "type": "module", a browser script without type="module", or Jest without ESM transform).

Seen on: Node.js JavaScript

Meaning

Node decides module type from the file extension (.mjs / .cjs) and the nearest package.json "type". Browsers need <script type="module">. Test runners like Jest need a transform or ESM mode.

Common causes

  • package.json lacks "type": "module" while files use import
  • <script src="app.js"> without type="module"
  • Jest running untransformed ESM (often from node_modules)
  • ts-node / TypeScript module settings mismatch

⚡ Quick fix

  1. Add "type": "module" to package.json (or rename to .mjs)
  2. Use <script type="module"> in HTML
  3. Jest: use babel-jest/ts-jest transforms or Vitest
  4. Match tsconfig module/moduleResolution to your runtime

Detailed fix by platform

Node.js

  1. package.json:
    json
    {
      "type": "module"
    }

JavaScript

  1. Browser: <script type="module" src="/js/app.js"></script>.

How to diagnose

  1. Runtime — Node, browser, Jest or ts-node?
  2. Type — How does that runtime decide ESM vs CJS here?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.