Search code examples
javascriptes6-modules

Cannot use import statement outside a module (at index.js:1:1)


I have recently started learning JS, and I am trying to export a function from a module script to my main 'index.js' script. But I am "getting Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)" error.

Could someone please help me out?

I have tried using type = module. I am not sure what I am doing wrong. I have tried running the code in chrome and edge both, same error.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <script src="./shoppingCart.js" type="module"></script>
  <script defer src="./index.js"></script>
  <title>Modern JavaScript Development: Modules and Tooling</title>
</head>

<body>
  <h1>Modern JavaScript Development: Modules and Tooling</h1>
</body>

</html>

index.js

import * as shoppingCart from "./shoppingCart.js";
shoppingCart.addToCart("iPhone", 1);

shoppingCart.js

export const addToCart = function (product, quantity) {
  console.log(`${quantity} ${product} added to the cart.`);
};

Solution

  • You can only use import inside an ES Module.

    Since you're using import inside index.js, you need to tell the browser that it is also a module (as well as shoppingCart.js).

    Therefore, you need to add type="module" to the script element that loads your index file.