RequireJS module load timeout when using bundles

593 views Asked by At

Have require js working fine without the bundles. But whenever i use a bundle, i get timeouts for the modules i am trying to import.

Here is how i build the bundles with the asp.net mvc bundler/minifier

bundles.Add(new ScriptBundle("~/bundles/test").Include(
            "~/scripts/jquery-{version}.js",
            "~/scripts/bootstrap.js",
            "~/scripts/moment.js"));

bundles.EnableOptimizations = true;

Heres is the require js config in the cshtml file:

<script>
    require.config({
        baseUrl: "/scripts",
        paths: {
            jquery: "jquery-1.11.2"
        },
        waitSeconds: 20,
        shim: {
            bootstrap: {
                deps: ['jquery']
            }
        },
        bundles: {
            '@Scripts.Url("~/bundles/test").ToString()': [
                'jquery',
                'bootstrap',
                'moment'
            ]
        }
    });
    require(["app/main/test"]);
</script>

And the js for the page (app/main/test):

require(['jquery', 'moment'], function ($, moment) {
    console.log(moment().format());
});

Jquery, bootstrap and moment libraries are in the test bundle i have created, but i get load timeouts loading the page for moment.

Here's the chrome inspector error:

load timeout

Any ideas?

thanks in advance.

2

There are 2 answers

0
potatopeelings On

Just remove 'jquery' from your bundles

bundles.Add(new ScriptBundle("~/bundles/test").Include(
        "~/scripts/bootstrap.js",
        "~/scripts/moment.js"));
...
bundles: {
    '@Scripts.Url("~/bundles/test").ToString()': [
        'bootstrap',
        'moment'
     ]
}
...

You already have it specified in the paths

paths: {
    jquery: "jquery-1.11.2"
},

It seems require.js maps the modules to bundles so that once a module that is part of a bundle is loaded, that bundle is not loaded again.

0
Vishwanath On

This is happening because you are not requiring your bundle at all. Your require call has only jquery and moment. You have provided jquery file path, so requirejs uses that path to download and provide jquery module. But since there is no path definition for moment, it is only part of the bundle that you have created. So requirejs tries downloading moment by its module name as path and thus throws an error.

A simple fix for this is to require bundle itself.

require(['@Scripts.Url("~/bundles/test").ToString()'], function(bundle){
   //At this point jquery, moment and bootstrap will be loaded. 
});

You can choose to use jQuery, moment from global namespace in above example directly or you can try requiring them seperately in below example. I am not sure, but you may get into error with below example because of cyclic dependency.

require(['@Scripts.Url("~/bundles/test").ToString()', 'jquery', 'moment'], function(bundle, $, moment){
       //At this point jquery, moment and bootstrap will be loaded. 
    });