Requirejs configuration in different file

雨燕双飞 提交于 2019-12-10 02:51:58

问题


I am using requirejs. My main.js content is like following.

requirejs.config({
    async: true,
    parseOnLoad: true,
    packages: [],
    paths: {
        jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min'
    }
});

require(["login"], function (loginService) {

    loginService.login('validUser');

});

Now, my config elements are little. But later, I will add packages, paths and others, so the require.config lines will increase.

  1. I wanna separate require.config as a different file and use it?
  2. If jquery load delays, does the error occurs? My other javascript files are using it.

回答1:


Yes you can, require your config before you require anything else, like this:

config example:

require.config({
    baseUrl: '/Public/js',
    paths: {
        jquery: '../../Scripts/jquery-1.10.2.min',
        jqueryui: '../../Scripts/jquery-ui-1.10.2.min',
    },
    shim: {
        jqueryui: {
            deps: ['jquery']
        },
    }
    waitSeconds: 3
});

and, then I load it:

require(['/Public/js/config.js'], function() {
    require(['home/index'], function() {                
    });
});

Just remember that you reference the config.js by path in the first require-statement because require.js can not resolve by baseUrl since it has not been loaded. When you get to the inner require()-statement, its loaded and you can reference dependencies relative to baseUrl.




回答2:


  1. You can put the config into a separate JS file, that's not a problem. Just make sure that file is loaded prior to the require() call in your main code.

  2. If you're using jQuery for other scripts that are not loaded via requireJS, you will get errors if they happen to load sooner than jQuery. What you need to do is convert all those static files into requireJS modules and load them all via requireJS. By using a define() function in each of the modules, you can set up dependencies, so all modules will wait for jQuery to load prior to executing their own code.




回答3:


This is an example of a multipage requirejs based project where the requirejs.config call is in a separate file

https://github.com/requirejs/example-multipage/tree/master/www



来源:https://stackoverflow.com/questions/18653492/requirejs-configuration-in-different-file

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