✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
The error “cannot use import statement outside a module” occurs when you use the import statement outside an ES (ECMAScript) module.
If you’re using Node.js, you need to set Node’s module system to ES modules – by adding type: "module"
to your package.json
file. However, if you’re getting this error in your web browser, add type="module"
to your <script>
tag.
Here’s what the error looks like in the Node.js environment:
(node:40660) Warning: To load an ES module, set type: module in the package.json or use the .mjs extension.
(Use to show where the warning was created)
/var/www/node-test/app.js:1
import { isOdd } from './utils.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
And in the browser:
How to fix "cannot use import statement outside a module" error
As mentioned earlier, this error can happen in two environments:
- Node.js
- Web browser
Let's see how we can fix the issue on either of these environments.
Node.js: Node.js supports two module systems for loading modules:
- The CommonJs Modules (the default module system)
- ES Modules
If you're getting the error in Node.js, the reason is probably Node.js isn't configured to use the ESM module system. Node's default module system is CommonJS, where you export modules with module.exports
and load them via require()
.
Set Node's module system to ES modules by adding "type": "module"
to your package.json
file.
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"type": "module",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC"
}
If you don't have a package.json
file yet, you can create one by running npm init
in your project's directory.
npm init
Npm will ask you to provide information about your package, such as name, version, description, author, etc. This information is optional, though.
The above should fix the issue in your Node.js app.
If you're getting the error in the browser: Most browsers have native support for ECMAScript Modules. However, if you get this error in your browser, you need to add type="module"
to your <script>
tag:
<script src="./main.js" type="module">
And in case you want to write your code directly in the HTML document:
<script type="module">
// Your JavaScript code here
</script>
Alright, I think that does it! I hope this quick guide could solve your problem.
Thanks for reading.
❤️ You might like:
- I got TypeError: getElementById is not a function in JavaScript (Resolved)
- I ran into "__dirname is not defined in ES module scope" (Fixed)
- Cannot find module error in Node.js (Fixed)
- SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)
- How to fix "ReferenceError: document is not defined" in JavaScript
Top comments (0)