The error, verbatim
Jump to the fix ↓SyntaxError: Cannot use import statement outside a module
Uncaught SyntaxError: Cannot use import statement outside a module
Tested on
- Node
- 24.14.0
- Browser
- Chrome 152
- OS
- Windows 11 Pro
The fix
The file uses import, but whatever runs it treats it as a classic script or CommonJS. Tell it the file is a module.
In the browser
Add type="module" to the script tag:
<script type="module" src="app.js"></script>
Module scripts don’t load from file:// pages. Open the page through a local server (for example npx vite or npx serve) instead of double-clicking the HTML file.
In Node
Use one of these:
// package.json
{ "type": "module" }
or rename the file to .mjs.
When does it still happen on Node 24?
Node 24 detects import syntax on its own, so the error is rarer than older answers suggest. From the reproductions:
| File | package.json | Result on Node 24 |
|---|---|---|
app.js |
no "type" field |
Runs, with a MODULE_TYPELESS_PACKAGE_JSON warning |
app.js |
"type": "commonjs" |
SyntaxError |
app.cjs |
anything | SyntaxError |
app.js |
"type": "module" |
Runs |
app.mjs |
anything | Runs |
So on current Node you’ll usually see it when a project is explicitly CommonJS, or when a tool runs your code as CommonJS. Older test and TypeScript setups often do that.
The warning in the first row goes away when you add "type": "module". That also skips a second parse, which Node says costs performance.
Why it happens
JavaScript has two loading modes. import and export only exist in ES modules. Browsers treat <script> without type="module" as a classic script. Node treats a file as CommonJS when package.json says so, when the file is .cjs, or on older Node, by default.
What didn’t work
— N.K., end of entry No.001