0

array_test.js:

export const output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

index.js:

import output from "./array_test.js"

Error:

index.js:1 Uncaught SyntaxError: Cannot use import statement outside a module

I am trying to export my array from array_test.js to index.js, but I don't know why I am getting this error. How can I fix this error?

pratteek shaurya
  • 850
  • 2
  • 12
  • 34
  • 1
    [will this help you](https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import) ? – KcH Dec 04 '20 at 07:10
  • 2
    1. You probably need to enable modules for your setup. Where are you using this? Browser? Node? I assume Node - which is the version? 2. You either need to do `export default` or instead to `import { output }` - right now the export and import are mismatched. – VLAZ Dec 04 '20 at 07:11
  • 2
    Does this answer your question? ["Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6](https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import) – costaparas Dec 04 '20 at 07:11

1 Answers1

0

Depending in what environment you are you need to change some things.

When you have an .js file that exports something like this:

//array.js
export const output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Inside your HTML file you need to add the type module and then you can import it

<script type="module">
    import { output } from "./array_test.js"
</script>

Also, you do a named export. That means you need to import it exactly by its name again.

In case you use node.js you would need to go to your package.json and add a new property to it:

"type": "module"

After this it should work. Depending on what version your node.js has you would need to add the --experimental-modules flag when you execute it like: node index.js --experimental-modules

bill.gates
  • 14,145
  • 3
  • 19
  • 47