This error occurs when you use an import statement outside the JavaScript module system. Generally, you will find this error in a browser and Node.js environment.
To solve the error in the Node.js, you have to add "type": "module"
to the package.json file. By adding this, you can use ES6 import
and export
keywords.
{ ... "type": "module", ... }
After adding "type": "module"
, you can use import and export keywords in the module.
export function sum(a, b) { return a + b; }
import {sum} from './utils.js'; console.log(sum(3, 4)); //7
If a package.json file is not present in the project, then you add it by running npm init -y command.
$npm init -y
To solve the error in the browser, you have to add type="module"
to the script
element.
<html> <head> <meta charset="UTF-8" /> </head> <body> <script type="module"> import { sum } from './utils.js'; console.log(sum(3, 4)); </script> </body> </html>
export function sum(a, b){ return a + b; }