0

I have declare a class in a FoodItem.js file like

export default class FoodItem {

   constructor(name) {
      this.name = name;
   }

   methodOne() {
      //statement
   }

}

And then in index.js file (same directory as FoodItem.js) I do an import like

import FoodItem from './FoodItem';

When I run it, I got an error

Cannot use import statement outside a module.

Can anyone tell what is wrong with the export/import syntax?

mickl
  • 48,568
  • 9
  • 60
  • 89
  • Does it work when you attempt to do the same thing with `require`? – Aarni Joensuu Apr 16 '21 at 09:00
  • The problem seems to be in the index.js. Check if this helps: https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import – Ajith Gopi Apr 16 '21 at 09:01

2 Answers2

0

Add a type="module" to your script tag.

Previous code:

<script src="./index.js"></script>

Updated Code:

<script type="module" src="./index.js"></script>
Muhammad Shaeel
  • 117
  • 2
  • 8
0

If you want to use imports inside HTML, make sure the type attribute is set to module, like this:

<sciprt type="module">
    import something from "./some-file.js";
</script>

Also, don't forget to include the path to the file relative to the current file, including the .js extension, if necessary.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37