Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access global variable in javascript?

I am trying to access a var one file from another file. Here is what I have:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>

  <body>
    <button id="btn">Global</button>
    <script src="/test.js"></script>
    <script src="/testpass.js"></script>
  </body>
</html>

test.js:

export var globalVariable = {
    output: "test this"
 };

testpass.js:

import { globalVariable } from './test.js'
document.getElementById("btn").addEventListener("click", function(){
  alert(globalVariable.output);
});

Nothing happens. I also tried doing

var globalVariable = {
    output: "test this"
 };

and then simply accessing it from another file as demonstrated in this answer: Call variables from one javascript file to another but it did not work. Tried exporting it as mentioned in this answer: Can I access variables from another file? as well but no success. I am using sublime text and vue.js and it does not work for both of them.

In addition if I do something like this:

import { globalVariable } from '.test.js'
document.getElementById("btn").addEventListener("click", function(){
  alert("Not printing the globalVariable here");
});

the entire javascript file seems to fail and doesn't work at all when called in the HTML file.

like image 667
h7651 Avatar asked Mar 06 '23 05:03

h7651


1 Answers

You should be getting an error from the browser's JavaScript engine in the web console. To use import and export, you have to treat your code as a module. Your script tags don't, they treat the code as just script. To treat testpass.js as a module, you must use type="module":

<script src="/testpass.js" type="module"></script>

No need to list test.js, testpass.js will load it. So:

<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
    <button id="btn">Global</button>
    <script src="/testpass.js" type="module"></script>
  </body>
</html>

Sadly, we can't show modules in SO's Stack Snippets, but if you make those changes, this codesandbox example is what you end up with (except I changed src="/testpass.js" to src="./testpass.js").


Note that globalVariable isn't a global variable (which is a Good Thing™). It's a local variable within test.js that it exports. Any other module can import it, but it's not a global.

like image 50
T.J. Crowder Avatar answered Mar 16 '23 11:03

T.J. Crowder