4

According to SO question Global javascript variable inside document.ready, I should be able to use global variables inside jQuery's document ready function. How can I do the same when my variable is declared inside a module?

<script type="module">
        import settings from './config/settings.js';
        var DAPP_VERSION = settings.version;
</script>
<script type="text/javascript">
var OTHER = 4;
</script>
<script type="text/javascript">
        $(document).ready(function() {
        console.log(OTHER);
        console.log(DAPP_VERSION);
    }); 
</script>

The above gives me:

Uncaught ReferenceError: DAPP_VERSION is not defined

config/setting.js contains:

export default {
    version: "1.1",
    rounds: 3,
    cars: 20,   
    lapLenght: "short"
}
Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224
  • 1
    Do you test this: `window.DAPP_VERSION=...`? – Hassan Sadeghi Jul 28 '18 at 12:56
  • @HassanSadeghi That won't work...and it is advisable to know if suggested solutions work before posting them, and if you tested it yourself, you'd know it didn't – Asons Jul 28 '18 at 13:04
  • I am in metro(subway) and I'm typing with mobile phone. I did not have a tool for test it. Sorry. – Hassan Sadeghi Jul 28 '18 at 13:22
  • 1
    Why not just put the `$(document).ready(…)` in a ` – Bergi Jul 28 '18 at 13:38

1 Answers1

2

When you use the type="module" declaration the variables are not attached to the global scope automatically but to the module scope (that is different).

You have to attach them explicitely to window in order to avoid ambiguity and make them visible across the whole application.

window.DAPP_VERSION = settings.version;

http://jsfiddle.net/R6FNs/572/

Karim
  • 8,454
  • 3
  • 25
  • 33