Search code examples
javascriptjqueryrequirejsbootbox

requirejs export global variable


I am trying to use bootbox (http://bootboxjs.com) with requirejs.

main.html

<script>
var require = {
    baseUrl: 'js',
    paths: {
        "jquery"    :['jquery-1.11.0.min'],
        "bootbox"   :['bootbox.min'],
        "bootstrap" :['//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min']
    },
    shim:
        'bootstrap' :{deps:['jquery']},
        'bootbox'   :{deps:['bootstrap'],exports: 'bootbox'}
    }
}
</script>
<script src="require.min.js"></script>
<script src="myscript1.js"></script>

main.js

define(['bootbox'],function(bootbox){
    bootbox.alert("Hello world!"); // working properly
});

myscript1.js

require(['main'],function(){
    bootbox.alert("Hello world!"); // not functioning (bootbox is not defined)
});

Normally once bootbox plugin is loaded, we can use bootbox anywhere on the page with this: bootbox.alert("Hello world!"); When using requirejs, I have to pass the bootbox variable and define it everytime when using requirejs in order to use bootbox. I have tried with "exports", but it doesn't seem help.

How can we have the bootbox variable available globally once it is loaded?

Thank you.


Solution

  • If you want Bootbox to be available globally you should include it manually with a script tag. RequireJS doesn't expose it.

    However, I highly recommend against this. The whole idea of dependency frameworks such as RequireJS is that you don't define anything on global scope, but to make your dependencies explicit. This not only allows you to lazy load scripts, but it also makes it possible to later replace dependencies, e.g. for unit testing.

    EDIT: As Louis correctly mentioned Bootbox already has AMD support. If it detects RequireJS (or any other AMD loader) it doesn't expose anything to the global scope, but since it has AMD support you also don't need to shim it.