Search code examples
javascriptimportexportsyntax-errorunexpected-token

Uncaught SyntaxError: Unexpected token 'export', but module 'import' still works


I'm confused here. I'm a newbie.

index.html

  <script src="appearance.js"></script>
  <script src="table-gen.js" type="module"></script>

appearance.js

  export const genModBtn = document.querySelector('.gen-mod-btn-container button');

table-gen.js

  import { genModBtn } from "./appearance.js";
  console.log(genModBtn);

Why am I getting this 'Unexpected token' if all seems to be working fine?

The import { genModBtn } from "./appearance.js"; seems to be working fine since console.log(genModBtn) is working too.

I've tried to remove export from export const genModBtn = document.querySelector('.gen-mod-btn-container button'), but without it, all stops working and it still log a different error.

What am I doing wrong here? Thank you in advance!


Solution

  • You should mark both of them as modules:

    <script src="appearance.js" type="module></script>
    <script src="table-gen.js" type="module"></script>
    

    The rest of the syntax seems fine. You can also use global variables like this:

    // appearance.js
    window.genModBtn = document.querySelector('.gen-mod-btn-container button');
    
    // table-gen.js
    console.log(genModBtn);