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

Can't access variables imported in html module script in other non-modules (FaunaDB imported)

Been trying to use FaunaDB in my website, and i cant seem to figure out much, ChatGPT has helped me for the most part but it can’t help here for some reason… heres my current code:

const client = new Client({
secret: '...nope i am not gonna let someone have my key...',
});

async function RunQ(query) {
try {
    // Run the query
    const result = await client.query(query);
    return JSON.stringify(result, null, 2);
} catch (error) {
    // Handle errors
    return new Error(error.message);
}
}

// here us an example function
async function CreateUser() {
const query = fql`
users.createData({
email: 'me@gmail.com',
pass: 'pass1',
totals: {
}
})
`;
await RunQ(query);
}
<script type="module">import{Client,fql}from'https://cdn.jsdelivr.net/npm/fauna@latest/dist/browser/index.js';console.log(fql ? 'MODULE LOADED' : 'FAILED TO LOAD MODULE')</script>
<script src="./main.js"></script>

It logs ‘MODULE LOADED’, but when i run CreateUser() it errors that ‘fql not found’.

Does this have to do with the fact that it is a module? I don’t know what’s wrong and I’ve been trying to fix it for a while now, so thanks in advance!

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

>Solution :

Tern Systems, here is a thoughtful answer for that Stack Overflow question:


Short Answer
In modern JavaScript modules (<script type="module">), variables are scoped to the module itself and are not automatically attached to the global object (window). Consequently, code in a non-module script cannot directly access variables imported or declared in a module script. You need to explicitly export them from your module or attach them to the global object if you want to share them with non-module scripts.


Detailed Explanation

  1. Module Scope Isolation
    When you use <script type="module">, any variables, classes, or functions declared within that script are module-scoped. They do not leak into the global scope the way variables in normal <script> blocks do. This design prevents unexpected collisions and promotes better encapsulation.

  2. Why You Can’t Access Module Variables in Non-Modules

    • Non-module scripts (or the console if you’re testing directly from a browser DevTools console) look for variables on the window object, which by default only contains variables declared in global scope.
    • If your script is a module, anything declared inside remains within the module’s local scope unless explicitly exported.
  3. How to Expose Variables from a Module
    If you want non-module scripts (or the global scope) to see your module’s variables:

    • Attach to the window object
      // Inside your module:
      const myValue = 42;
      window.myValue = myValue;
      

      Now a non-module script (or even inline code in the HTML) can do:

      console.log(window.myValue); // 42
      
    • Import/Export Mechanism (for module-to-module communication)
      If both scripts are modules, you could export from one module and import in another:

      // moduleA.js
      export const myValue = 42;
      
      <!-- moduleB -->
      <script type="module">
        import { myValue } from './moduleA.js';
        console.log(myValue); // 42
      </script>
      
  4. Ensure Consistent Script Types

    • If you’re mixing module scripts and non-module scripts, be aware that variables declared in one scope aren’t automatically available in the other.
    • For certain projects, it’s simpler to keep all scripts as modules for consistent import/export patterns.

Practical Recommendations

  1. Convert Dependent Scripts to Modules
    Whenever possible, convert all <script> tags to type="module">. This way, you can leverage JavaScript’s native module system, using export and import as intended.

  2. Use the Global Object Only When Necessary
    If you genuinely need global access—like for a quick proof of concept—attaching to window is a simple approach. However, from a design standpoint, global variables can lead to naming collisions and maintenance issues. Use them judiciously.

  3. Check Browser Support
    Most modern browsers fully support <script type="module">, but you might need to transpile or use polyfills for older environments. Keep that in mind if you’re targeting legacy browsers.


Module scripts are designed to provide a more robust and encapsulated code structure. If you need to share variables with non-module scripts, explicitly assign them to the global scope or refactor your code to use only modules. By following the import/export standards, you’ll maintain cleaner, more maintainable code.

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