Node.js Diagnostic

Fix "SyntaxError: Cannot use import statement outside a module" in Node & Jest

Node.js treats files as CommonJS by default (requiring require/module.exports). When it encounters ES Module "import" syntax without "type": "module", it crashes with SyntaxError.

SyntaxError: Cannot use import statement outside a module

Quick Fix Checklist

  1. In package.json: Add "type": "module"
  2. Or rename your script file extension from .js to .mjs
  3. In HTML: Use <script type="module" src="./main.js"></script>
  4. For TypeScript scripts: Run with "npx tsx script.ts" instead of plain node