node · JavaScript
The message
SyntaxError: Cannot use import statement outside a module
What it means
Node or the browser read that file as a CommonJS script, and it contained the ESM keyword import. A .js file is CommonJS unless package.json declares otherwise, and in a browser the same thing happens when the <script> tag has no type="module". npm pkg set type=module declares the whole package as ESM and clears it, but from that moment every .js in the package loses require and __dirname, so the remaining CommonJS files must move too — if you only want to convert one file, renaming it to .mjs is the narrower and safer change.
The fix
npm pkg set type=module- Printed by
- node
- JavaScript
- 15
Browser and Node errors usually tell you what broke and not why the value became what it was — you read undefined, it was not a function, it was not JSON — so the place to fix is upstream of the line that threw, and silencing just that line with ?. and default values makes the same problem reappear further away in a form that is harder to recognise.
Reading an error message
- Read from the first line down. The lower you go the more it is about the tool’s internals; the cause is usually at the top.
- If there is a file and a line number, start there — not the top stack frame, but the topmost line that names a file you wrote.
- Search the message verbatim, but strip your own paths and variable names first; those are what stop the search from matching.
- The same condition is worded differently across tool versions. If results look wrong, add the version number to the query.
- Before pasting a fix, check what it throws away. Some of these cannot be undone.
Common questions
Q. What does “SyntaxError: Cannot use import statement outside a module” mean?
Node or the browser read that file as a CommonJS script, and it contained the ESM keyword import. A .js file is CommonJS unless package.json declares otherwise, and in a browser the same thing happens when the <script> tag has no type="module". npm pkg set type=module declares the whole package as ESM and clears it, but from that moment every .js in the package loses require and __dirname, so the remaining CommonJS files must move too — if you only want to convert one file, renaming it to .mjs is the narrower and safer change.
Q. How do I fix it?
npm pkg set type=module — before running it, check the explanation above for what this command discards.
Q. Which tool prints this?
node. It sits under JavaScript, and the message runs to 8 words.