How to fix 'Uncaught SyntaxError: Cannot use import statement outside a module'
Johnny Simpson
Posted on August 7, 2022
In this quick guide we'll look at how you can solve the very common error, "Uncaught SyntaxError: Cannot use import statement outside a module". This error arises when we try to use import
inside of a project which is not set up for modules - so let's look at how you can resolve it.
Resolving the import statement outside a module error
The reason why this error occurs is because we have to explicitly tell Javascript that the file in question is a module
, in order to use the import
statement. For example, if you are using the line below, and you have not told Javascript that the file is a module, it will throw an error:
import fs from 'fs'
Depending on where you are getting the error, there are a few different ways to resolve it.
Resolving the import module error in Node.js
If you are using Node.js, this error can be resolved in two ways. The first is to update your package.json to tell Node.js that this entire project is a module. Open up your package.json, and at the top level, add "type": "module"
. For example, my package.json
will look like this:
{
// ... other package.json stuff
"type": "module"
// ... other package.json stuff
}
This will resolve the issue immediately. However, in some edge cases, you may find you have issues with this, and other parts of your code may start throwing errors. If you only want one file in your project to support import
, then change the file extension to .mjs
. For example, if your import
was in index.js
, rename index.js
to index.mjs
. Now your issue will be resolved.
Resolving the import module error in script tags
The second place this error can occur is in a script tag, like this:
<script src="mymodule.js"></script>
In this case, if mymodule.js
contains an import
statement, it won't work. To resolve this, add type="module"
to your script tag:
<script type="module" src="mymodule.js"></script>
Now you'll never have issues with import
again.
Posted on August 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 3, 2023