Home > front end >  HTML: using external .js file with import statements
HTML: using external .js file with import statements

Time:09-26

I have an HTML file ~/docs/index.html which has an internal JavaScript script to allow input/output with two text areas. This internal JS script, in turn, calls an external JS script ~/src/Main.js which I have imported in the head of my HTML file.

Everything seems to work great, until my ~/src/Main.js needs to import other external JS files. Then, things no longer seem to work.

~/docs/index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <base href="../" target="_blank">

    <!-- JavaScript imports -->
    <script type="module" src="src/Main.js"></script>
  </head>

  <body>
    <main>
      <div>
        <textarea
          id="input"
          oninput="update()"
          placeholder="Type here!"
        ></textarea>
        <textarea id="output" readonly>no way</textarea>
      </div>
      
      <!-- Textarea script -->
      <script>
        // Updates the textarea
        function update() {
          let input = document.getElementById("input");
          let output = document.getElementById("output");
      
          output.value = doubleIt(input.value);
        }
      </script> 
    </main>
  </body>
</html>

~/src/Main.js:

import "./OtherClass.js";   // THIS LINE BREAKS THINGS

export function doubleIt(input) {
  return input   input;
}

I've seen this question but the solutions there don't seem to work for me. Any help appreciated.

CodePudding user response:

Every script that uses the import / export syntax that is included in the DOM must have type="module" attribute.

If the inline script uses any functions from a module, then they also need to be imported first.

Note: avoid inline event listeners like oninput and add event listeners through JavaScript, as with modules the update function will no longer be a global value.

<script type="module">
  import { doubleIt } from "./src/Main.js";

  let input = document.getElementById("input");
  let output = document.getElementById("output");

  function update() {
    output.value = doubleIt(input.value);
  }

  input.addEventListener('input', update)
</script>
  • Related