RequireJS Setting Path to the Parent Level

放肆的年华 提交于 2019-12-12 04:13:46

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/11816553/requirejs-setting-path-to-the-parent-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!