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?

2

3 Answers 3

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'
});
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent! Thank you very much. But one correction: App.model.get('foo');
Edited to match the example. Thanks for accepting the answer!
1

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

Comments

-1

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

3 Comments

Oh. I don't understand you. Can you show an example?
require(['app','jquery', 'backbone', 'underscore']); requires Underscore.js. Download and link to it as you would any other JS file.
I've downloaded Underscore.js. It is in folder with other scripts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.