4

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.

h7651
  • 59
  • 3
  • "Nothing happens" means that not even the alert window appears? – messerbill Oct 24 '18 at 15:30
  • Don't use es6 modules much myself, but I seem to recall that you need a `type=module` on the script tag for it to be treated as a module – David784 Oct 24 '18 at 15:30
  • At least related: https://stackoverflow.com/questions/39944861/should-i-reference-files-in-a-script-tag-when-using-es6-modules-in-a-browser – T.J. Crowder Oct 24 '18 at 16:16

1 Answers1

7

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639