Cannot Use Import Statement Outside a Module | Fix

If you are working with JavaScript or any javascript frameworks like react, node js, etc. Then you might get this type of syntax error. Saying, “cannot use import statement outside a module.” In the article, I will tell you about fixing it. And all the methods to avoid this type of error. Just see which one works best for you. 

Why can't you use an import statement outside a module?

The reason for this error is that the syntax is not right in the source code. As the error says, you can't use import statements outside a module. That means the import statement should be inside the module. It depends on the versions and the bundle. It would help if you were using the syntax that is present in the documentation. 

If you are not using a bundled version, I recommend that you use the bundled version. You should use the native source code only in a bundled method. When you try to use it in an unbundled way, you might come across this type of Uncaught Syntax error. Just follow the documentation and do not mix the form of coding for different packages and bundles. By doing so, you will prevent this type of syntax error in the future.

In other words, you are linking to the file of an unbundled version. In that case, you use npm to get the bundled version. Before trying to fix anything, make sure to update all your files, such as dependencies, packages, libraries, etc.

How to fix the import statement?

Fix 1: Add “ Module “ in the script type

You can do this for both internal and external files. Change the script-src line as shown below. Just add type=" module" in-between type and src.

Save the file and restart the server

Fix 2: Add “Type Module” in the package.json file

Look for the package.json file inside the folder. And in the lines of code, search for the piece of code below. If you don't find it, then place this code. And see if it works for you.

{  "type": "module", }

Fix 3: Use import in the module

Inside the module, add the import statement with the script location in the directory. Try it and see if it works for you.

Fix 4: Use require instead of import

Instead of using the import statement, use require both almost work the same way. But you have to change the syntax of the code. Just follow the code below. And you are good to go.

import filename from 'filename';const filename = require('filename');

Final thoughts

I hope this tutorial helped your errors in some way. As the versions of the language progress, the syntax of the source code slightly changes as well. Just try these fixes and see which one works for you. This error generally occurs when you switch frameworks, languages, or even versions of the same programming language. Once you get the hang of it, you will fix these errors of your own. 

Also Read: