Rajkamal Subramanian
Rajkamal Subramanian

Reputation: 6964

require js shim not working for this code

I have the following code.

<script src="js/libs/require.js"></script>
<script>
    requirejs.config({
        baseUrl:'js/modules/',
        paths:{
            'bbn':'../libs/backbone',
            'underscore':'../libs/underscore'
        },
        shim:{
            'bbn':{
                exports:'B',
                deps:['underscore']
            }
        }
    })  
    requirejs(['bbn'], function(B){
        console.log(B)
    });
</script>

The function parameter B is not pointing to Backbone. Instead its getting logged as undefined.

I followed the following post and arrived to this point:

Loading Highcharts via shim using RequireJS and maintaining jQuery dependency

I see both underscore and backbone JavaScript files getting downloaded in firebug.

Upvotes: 4

Views: 4417

Answers (2)

John Paul Barbagallo
John Paul Barbagallo

Reputation: 452

The latest version of Underscore (~1.6.0 as of writing this) is AMD-compatible. Do not use it as a shim or you may run into issues.

Upvotes: 1

Simon Smith
Simon Smith

Reputation: 8044

Underscore is not AMD compat either, so make sure you shim that too:

requirejs.config({
baseUrl:'js/modules/',
paths:{
    'bbn':'../libs/backbone',
    'underscore':'../libs/underscore'
},
shim:{
    'bbn':{
        exports:'Backbone',
        deps:['underscore']
    },
    'underscore': {
        exports: '_'
    }
}
})  
requirejs(['bbn'], function(Backbone){
console.log(Backbone)
});

You will see Underscore being downloaded but because it not defined as a proper module RequireJS just treats it as a normal JS file and doesn't get a return value

Upvotes: 6

Related Questions