Single File HTML: Importing function from module within the same doc

169 views Asked by At

I've got a form trying to access two functions that's located all within the same HTML document. The function, dependent on firebase needs to be a module in order to import initializeApp, getFirestore etc.

HTML

<input type="button" onclick="formSubmit(); dataSubmit(); return false;">

Vanilla JS

 <script>
   const formSubmit = () => {
      //works perfectly
   }
 </script>

<script type="module">
   import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
   import { getFirestore, collection, addDoc } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-firestore.js";

   const firebaseConfig = {
    ...
   };
   const app = initializeApp(firebaseConfig);
   const db = getFirestore(app);

   export const dataSubmit = () => {
      ...
   }
</script>

Error: "ReferenceError: Can't find variable: dataSubmit"

It would be much simpler if. I could import it from another file but for the purposes of meeting client requirements I need to keep everything in this HTML file...

Any advice?

1

There are 1 answers

0
Pointy On BEST ANSWER

You should really follow Quentin's advice in the linked duplicate, but you can expose module "globals" by explicitly creating window properties:

const dataSubmit = () => {
  ...
};
window.dataSubmit = dataSubmit;
export dataSubmit;

This will work, but the whole point of modules and their global behavior is to avoid the long-standing problem of window namespace pollution.