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
- In package.json: Add "type": "module"
- Or rename your script file extension from .js to .mjs
- In HTML: Use <script type="module" src="./main.js"></script>
- For TypeScript scripts: Run with "npx tsx script.ts" instead of plain node