Method 1: Using Module in Package.JSON file
The first method that you can use the get rid of this error is using the
"type":"module" code in your package.json file present inside your project folder.
As you can see in the above code, I have used the import syntax function instead of
require method that can usually cause the SyntaxError. Hence to remove this syntax error you need to import the module in the package JSON.
Also, make sure that you do not run TypeScripts scripts present in your project independently as those scripts can also cause this error or you can go into an infinite loop instead.
Method 2: Adding Module to Script Tag
If you are still getting the error then you may try adding the type as a module in the script tag as well. Sometimes adding a module to a package JSON file may not work and it may work if you add it to an individual script tag that is throwing an error for you.
<script type="module" src="../src/main.js"></script>
Method 3: Using Require Instead of Import
You can use the
//Suppose you want to import fetch from 'getFetch'
fetch = require('getFetch')
Note: Here inside the bracket after require you need to enter your library name and before equals what you want to import from that library.
Using the above code, I was able to fix my error for SyntaxError for importing the module. This usually works for Node.
Method 4: Enable EMCAScript 6 in NodeJs
Another method that can help you fix this SyntaxError is enabling the ECMAScript 6 in your project if it is already not enabled. To enable you to need to follow the below steps.
//Open the Terminal and Type and Press Enter
npm install --save esm
node -r esm server.js
Why SyntaxError: Cannot use import statement outside a module Occurs?
The SyntaxError: Cannot use import statement outside of a module error could occur if you attempt to execute the file independently. You have not yet installed and configured an ES6 compiler such as Babel, or the file path in your runscript is incorrect/is not the compiled file.
If you wish to proceed without using a compiler, the optimal way is to use ES5 syntax, which in this example would be var ms = require(./ms.js);. This can be updated later as necessary, or better yet, configure your compiler and ensure that your file/project is compiled prior to running. Additionally, ensure that your run script is running the compiled file, which is typically named dist, build, or whatever you named it and that the path to the compiled file in your runscript is correct.
I hope you were able to fix the SyntaxError using the methods listed above. As to resolve this error I have listed around four methods that you can use to resolve this issue.
If you are still not able to resolve this issue then please let me know in the comment section. Also, let me know if you know a better method to resolve these issues other than the one discussed above I will be happy to add it here.