Garrett
Garrett

Reputation: 11745

RequireJS Setting Path to the Parent Level

In order to direct my models, collections, etc. from my mobile app to my web app, I need to configure my RequireJS.

I have the following file structure:

/
/js
  /models
/mobile
  /js
  /templates

I want my mobile app to use my main app's models, so I set the following:

require.config( {
    paths : {
        models : '/js/models',
        templates : 'mobile/templates'
    }
});

And I get these errors in Chrome:

Uncaught SyntaxError: Unexpected token < /mobile/js/models/User.js?bust=0.1.0:1
Uncaught SyntaxError: Unexpected token < /mobile/js/models/InviteRequest.js?bust=0.1.0:1
Uncaught SyntaxError: Unexpected token < /mobile/js/models/Log.js?bust=0.1.0:1

Meaning that it's still looking in /mobile instead of /.

This path config works for my templates folder, but not my models folder. How can I point all require dependencies that start with models/ to my main models folder?

Thanks!

ATTEMPT 2

I tried setting the baseUrl instead:

require.config( {
    baseUrl : '/',
    paths : {
        views : 'mobile/views',
        templates : 'mobile/templates'
    }
});

require( [
    'app'
],
function(App) {
    App.initialize();
});

I get the error:

GET http://local.m.mysite.co/app.js 404 (Not Found) require.js:2

Upvotes: 0

Views: 4334

Answers (1)

stack247
stack247

Reputation: 5747

In your second attempt, you basically tell Require JS to load 'app' module and since you set the base url to '/', Require JS will look 'app' module in your root path.

So what you need to do is to tell Require JS where to look for your 'app' module. Say your 'app' module is in /js/module:

/
/js
  /models
  /module
    /app.js
/mobile
  /js
  /templates

Then your code to load 'app' module is:

require.config( {
    baseUrl : '/',
    paths : {
        views : 'mobile/views',
        templates : 'mobile/templates'
    }
});

require( [
  'js/module/app'
],
function(app) {
    app.initialize();
});

Alternatively, you can set 'module' path in your config. Then refer to this path in your dependency loading:

require.config( {
    baseUrl : '/',
    paths : {
        views : 'mobile/views',
        templates : 'mobile/templates',
        module: 'js/module'
    }
});

require( [
  'module/app'
],
function(app) {
    app.initialize();
});

As for the error you get in Chrome before your ATTEMPT 2, you will need to look at how you refer to your module in module loading.

Upvotes: 1

Related Questions