Search code examples
javascriptasch-development

Howto use a (global) variable from a module inside jQuery's document ready function?


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"
}

Solution

  • 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/