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.

3
  • "Nothing happens" means that not even the alert window appears? Commented Oct 24, 2018 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 Commented Oct 24, 2018 at 15:30
  • At least related: stackoverflow.com/questions/39944861/… Commented Oct 24, 2018 at 16:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.