SyntaxError: Cannot use import statement outside a module
This error is one of the most common issue if you are trying to use ES6 features in your JavaScript project. For eg: when you import a function from math.js inside main.js file, it throws " SyntaxError: Cannot use import statement outside a module " in you terminal. main.js
import math from 'math.js'
math.add()
Output: 
Add type="module" inside the script tag
When working with ECMAScript modules and JavaScript module import statements in the browser, you'll need to explicitly tell the browser that a script is module. To do this, you have to add type="module" onto any ‹script› tags that point to a JavaScript module. Once you do this you can import that module without issues.
<script type="module" src="./index.js"></script>
Add "type": "module" to your package.json
If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property "type": "module" as shown below.
{
// ...
"type": "module",
// ...
}
Use the extension .mjs in your files
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 order to solve this problem, use the extension .mjs in your files and use this command to run the file.
node --experimental-modules filename.mjs
Use import by required
In some cases, you may have to use both import and require statements to load the module properly.
// import { parse } from 'node-html-parser';
parse = require('node-html-parser');
If you're still getting the error even though you're using import in a module file, make sure that your JavaScript environment supports modules. Some older browsers and Node.js versions do not support modules natively, and you may need to use a module bundler like Webpack or rollup.js to transform your module code into a format that can be used in your environment.
Related Topics
- Uncaught TypeError: 'undefined' is not a function
- XMLHttpRequest cannot load no 'access-control-allow-origin'
- TypeError: null is not an object
- Uncaught RangeError: Maximum call stack size exceeded
- Uncaught TypeError: Cannot set property
- SecurityError: Blocked a frame with origin from accessing a cross-origin frame
- Unable to get property undefined or null reference
- What is UnhandledPromiseRejectionWarning