JavaScript SyntaxError: Cannot use import statement outside a module
A plain-words explanation of this JavaScript message: what it means, the usual causes, and the steps that fix it.
The messageUncaught SyntaxError: Cannot use import statement outside a module
Make the error yourself
Run in Google Chrome 157.0.8103.51. This is the smallest example we could find that shows it.
JavaScript (in a script tag)
import value from "data:text/javascript,export default 5";
console.log(value);Browser console (the real message)
SyntaxError: Cannot use import statement outside a moduleWhy it happens
import and export belong to JavaScript modules. A normal <script> tag in a page is not a module, and neither is a Node.js file with the .js extension unless the project is set up for it, so the engine does not understand the import word and reports a syntax error. The message appears when you copy modern code into an old setup, load a file that uses export with a plain script tag, or run an ES module in Node without telling Node.
How to fix it
- In a web page, mark the script as a module:
<script type="module" src="app.js"></script>. Modules are deferred automatically and need to be served over http, not opened as a file. - In Node.js, name the file
.mjs, or put"type": "module"inpackage.json. - Or use the older form
const x = require("x")in a CommonJS file. - As a quick workaround in a plain script, load a module with a dynamic
import("..."), as in the fixed example.
The corrected version
JavaScript (in a script tag)
import("data:text/javascript,export default 5").then(m => console.log(m.default));Browser console (the corrected version)
5How to avoid it
Decide at the start of a project whether it uses modules or not, and write that in the project setup.
Questions
Why does my module work on a server but not when I open the file?
Browsers do not load modules from file:// addresses because of security rules. Use a local server.
This is an independent guide. It is not connected with Python, Microsoft, Google, GitHub or the Git project. Product names belong to their owners. Examples were run on 13 November 2026 in a practice folder or a blank workbook; your version may word a message slightly differently.