Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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()
  })  
})
like image 997
Martin Valdez Avatar asked Nov 04 '25 07:11

Martin Valdez


2 Answers

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}
like image 184
Christian Fritz Avatar answered Nov 05 '25 20:11

Christian Fritz


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

<script src="example.js" type="module"><\script>
like image 33
Stephanie Egbuonu Avatar answered Nov 05 '25 22:11

Stephanie Egbuonu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!