Example, when we import a function from math.js inside main.js file. It throw us an error in our terminal.
import math from 'math.js' math.add()
Uncaught SyntaxError: Cannot use import statement outside a module
So to resolve this error, we can try two fixes.
To fix this error we just have to add type="module" as an attribute in the
<script> element of main.js. This declare the script as a module.
<script type="module" src="main.js"></script>
The script ( in this case main.js ) into which we import the modules acts as a top-level module.
You can also embed the module script in your HTML file , just place the import module scripts in the body inside the
If you don't use the
type="module" , in firefox browser it will show SyntaxError: import declarations may only appear at top level of a module error.
If you are using node application and want to use the import statement, then you will also get the "Cannot use import statement outside a module" error. It is because ES6 import and export statements are not support in node by default.
In node 9, you have to use
type="module" inside your package.json file, use .mjs extension and then
enable --experimental-modules flag and run:
node --experimental-modules main.js
Read full article on How to use es6 import statements in Node.js, if you are using node 12 or greater.
Troubleshoot : In node 9, if you get "ReferenceError: require is not defined" error, just use import syntax instead of require. You cannot use both import and require in your nodejs application. You have to pick one.