I recently was working with a third-party library. I ran into the error “Uncaught SyntaxError: cannot use import statement outside a module” when I tried to import a function from the package. Let us look into why it occurred and how I fixed it.
The error description “Uncaught SyntaxError: cannot use import statement outside a module” gives us some hints as to what is happening, but it is still unclear what the exact error is. It occurs when we are trying to use “import” inside a non-ES module. The error can occur in both Node.js environments and packages being imported in the browser. You can read more about ES modules in this post if you are unfamiliar with them.
So whenever we try to import a CommonJS module, we will get the error: “Uncaught SyntaxError: cannot use import statement outside a module“.
Now that we understand the why, let us look into potential solutions.
Let us assume we were importing the function hello
from wisdomgeek.js
. Then, the line that was causing the error would have been:
import { hello } from './wisdomgeek.js';
JavaScriptThis would then be replaced by:
const { hello } = require('./wisdomgeek.js');
JavaScriptThis is the most naive solution, but we cannot natively mix and match between ES modules and CommonJS modules. We can configure our bundler to make it work with both modules, but that can cause more problems than it solves.
We want to convert the CommonJS package to use ES Modules without changing its source code. Luckily, there is a way to tell Node that our project uses ES modules no matter what the third-party package is written as. For this, we need to add a property in our package.json
file:
{
"type": "module"
}
JavaScriptAfter doing this, the import statement should work without any errors.
import { hello } from './wisdomgeek.js';
JavaScriptWhile the above solution works for Node.js, it does not work if we import the package inside a script tag. We can specify the type as an attribute on the script tag to resolve these errors. So, the import:
<script src="wisdomgeek.js"></script>
JavaScriptBecomes:
<script type="module"src="wisdomgeek.js"></script>
JavaScriptThose are all the solutions to solving the “Uncaught SyntaxError: cannot use import statement outside a module” error. Let us know in the comments section if it helped resolve your error.
I am terrible at optimizing my keyboard layout for anything. But off lately, my little…
I recently switched completely to the Brave browser and have set ad blocking to aggressive…
I was preparing a slide deck for a hackathon and decided to put in a…
I have been using npx a lot lately, especially whenever I want to use a…
Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…
While working on a project, I wanted to do an integrity check of a file…
View Comments
Great post.
Thank you for leaving a comment. Glad it helped.