Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading