简体   繁体   中英

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM