3

Hi i'm using requirejs to just organize my javascript codes into AMD modules, i'm building a non-single page website right now using codeigniter, what i do is i have a default layout html file which i always call to render the dynamic content of the body so my script which call the requirejs and has the data-main attribute is encoded on my layout html page.

<script data-main="<?=base_url('assets/js/main.js');?>" src="<?=base_url('assets/js/require.js');?>"></script>

and my main.js looks like this.

requirejs.config({
baseUrl: "assets/js",
paths: {
    jquery: 'vendor/jquery',

    bootstrap: 'vendor/bootstrap',

    datatables: 'vendor/jquery.dataTables'

},

shim: {
    jquery: { exports: '$' },
    datatables: { deps: ['jquery'] }
}
});

requirejs(['bootstrap','datatables'], function(){

})

so when i type on my url "localhost/ci-project/" it will load the layout page together with the dynamic body. On this scenario it works fine. sicne requirejs will render the path correctly "localhost/ci-project/assets/js/vendor/[js file/module]"

but when i change the URL to say, 'localhost/ci-project/welcome/admin'. what requirejs do to load the modules is concatenate the baseUrl + module path, to the current URL which in this case is 'localhost/ci-project/welcome/admin' and ending result is like this:

'localhost/ci-project/welcome/admin/assets/js/vendor/[module]' which is wrong.

so how can i configure requirejs to always load the from the root url and then concatenate the baseUrl value together with the paths of each modules?

4

2 回答 2

3

The way to solve this is to output the baseUrl from a server side variable.

In your PHP page:

<script>
var require = {
    baseUrl: '<?= base_url(); ?>' // Or whatever outputs the full path to your site root
};
</script>
<script data-main="<?=base_url('assets/js/main.js');?>" src="<?=base_url('assets/js/require.js');?>"></script>

Creating a require object before RequireJS is loaded allows you to define config options that will be picked up automatically.

Calling require.config() again from inside main.js is fine, it will just add the additional config options, but be sure to remove baseUrl from there.

于 2013-08-22T11:48:46.443 回答
1

Simon's answer above helped when I had issues with navigating to routes with parameters - relative paths to base url go wrong. I am using asp .net mvc, but the solution is exactly the same: (_Layout.cshtml)

<script>
    var require = {
        // by default, load any module IDs from
        baseUrl: '@Url.Content("~/Scripts/lib")'
}
</script>
<script data-main="@Url.Content("~/Scripts/application/app.js")" src="@Url.Content("~/Scripts/lib/require.js")"></script>
于 2015-01-08T02:22:00.173 回答