0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Michael Martell
  • 141
  • 2
  • 16
  • Module-scoped variables are not visible as `window` properties unless your module explicitly makes them: `window.dataSubmit = dataSubmit;` if you absolutely must use inline event handlers. – Pointy Nov 23 '22 at 19:16
  • your amazing. It worked. Please write an official answer so I can give you credit! – Michael Martell Nov 23 '22 at 19:20
  • I was looking for a duplicate but I'm terrible at finding them. I'll add an answer if I can't find a good one. – Pointy Nov 23 '22 at 19:21

1 Answers1

1

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614