0

I want to create Backbone.js app with Require.js. But I have an error in console: Uncaught Error: Module name "underscore" has not been loaded yet for context: _. Use require([])

require.config({
        baseUrl: 'js/',
        paths : {
            'jquery' : 'jquery',
            'underscore' : 'underscore',
            'backbone' : 'backbone',
            shim: {
                'underscore': {
                    exports: '_'
                },
                'backbone': {
                    deps: ['underscore', 'jquery'],
                    exports: 'Backbone'
                }

            }
        }
    });

    define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){

        var Model = Backbone.model.extend({});
        var model = new Model;
    });

    require(['app','jquery', 'backbone', 'underscore']);

How I can resolve this problem?

Alexander Seredenko
  • 799
  • 3
  • 9
  • 26
  • try changing the order in define call to `jquery, underscore, backbone` – coding_idiot Feb 01 '15 at 10:46
  • possible duplicate of [Trouble combining Require.js and Backbone.js/Underscore.js](http://stackoverflow.com/questions/16774214/trouble-combining-require-js-and-backbone-js-underscore-js) – Louis Feb 01 '15 at 11:21

3 Answers3

1

The shim is mentioned inside the paths object. I am not sure if that is the problem, but wanted to mention that here.

Kumaran
  • 41
  • 4
1

You still need to list underscore as a part of paths so you can refer to it in the shims. Also, not sure what your directory structure looks like, but I'm writing this with the assumption that library code is in the /js/libs directory). Finally, note you won't need to require any of the dependencies of app -- the joy of RequireJS is that it'll figure out what to load.

So...

require.config({
    baseUrl: 'js/',
    paths : {
        'jquery' : 'lib/jquery',
        'underscore' : 'lib/underscore',
        'backbone' : 'lib/backbone',
    },
    shim: {
        'underscore': {
            exports: '_'
        },
       'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        }

    }
});

define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){
    var Model = Backbone.Model.extend({});
    var model = new Model({
        foo: 'bar'
    });

    var app = {
        model: model
    };

    // ...

    return app;
});

require(['app'], function(App) {
    App.model.get('foo'); // <<=== returns 'bar'
});
Peter Wagener
  • 2,073
  • 13
  • 20
-1

You need Underscore.js as listed in your require statement.

Will
  • 546
  • 5
  • 16