Martin Valdez
Martin Valdez

Reputation: 43

Uncaught SyntaxError: export declarations may only appear at top level of a module

Good afternoon, I was trying to export the values of 'nameValue' and 'passValue' to use them in another javascript file but I can't export them.

I get the following error:

Uncaught SyntaxError: export declarations may only appear at top level of a module

I am not using any framework or library (Javascript Vanilla only)

document.addEventListener('DOMContentLoaded', () => {
  console.info('This is running!')

  let name = document.getElementById('name')
  let password = document.getElementById('password')
  let loginBtn = document.getElementById('loginBtn').addEventListener('click', () => {
    nameValue = name.value
    passValue = password.value 

    export {nameValue, passValue}

    event.preventDefault()
  })  
})

Upvotes: 4

Views: 6920

Answers (3)

Nikhil kumar
Nikhil kumar

Reputation: 631

Don't include both script if you using export import to each other.

<script src="./assets/scripts/app.js" type="module"></script>
<script src="./assets/scripts/util.js" ></script>

Upvotes: 1

Stephanie Egbuonu
Stephanie Egbuonu

Reputation: 21

Check if you included a type=“module” attribute in the script tag

<script src="example.js" type="module"><\script>

Upvotes: 1

Christian Fritz
Christian Fritz

Reputation: 21384

The error is trying to say that you can use export only at the top level of your code, i.e., not in a function body or similar. Your variables will need to be defined at that level, too.

let nameValue, passValue;

document.addEventListener('DOMContentLoaded', () => {
  console.info('This is running!')

  let name = document.getElementById('name')
  let password = document.getElementById('password')
  let loginBtn = document.getElementById('loginBtn').addEventListener('click', () => {
    nameValue = name.value
    passValue = password.value 

    event.preventDefault()
  })  
})

export {nameValue, passValue}

Upvotes: 4

Related Questions