0
votes

I'm trying to use Bootstrap with RequireJS, setting RequireJS' config like this:

  • js/

    • bootstrap.min.js
    • app.js
    • require.js
    • scripts.js

This is the app.js file:

requirejs.config({ 
  "shim": { 
    "bootstrap": {deps : 'jquery' } 
  }, 
  "paths": { 
    "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min", 
    "bootstrap" : "bootstrap.min" 
  }, 
  enforceDefine : true 
});

// Load the main app module to start the app 
requirejs(["scripts"]);

This is the scripts.js file:

define(["jquery", "bootstrap"], function($) {
    console.log(jQuery);
    $('#video').click(function () {
    var src = 'http://www.youtube.com/v/FSi2fJALDyQ&autoplay=1';
        $('#myModal').modal('show');
        $('#myModal iframe').attr('src', src);
    });  
    $('#myModal button').click(function () {
        $('#myModal iframe').removeAttr('src');
    });
});

This doesn't work and on the console says Bootstrap needs jQuery to work. The weird thing is if I change Bootstrap's path to load it from a CDN, it works.

2
Not positive here but I think I had a similar problem when using modals and I needed to include the bootstrap.js file instead of jquery. I think it says it needs jquery because bootstrap.js is a modified version of jquery. - ArtfulDodger

2 Answers

0
votes

Your shim for Bootstrap should use an array to specify dependencies:

shim: { 
    "bootstrap": {
        deps : ['jquery'] // Use an array even with a single dependency.
    } 
}

The way it is now RequireJS does not get the dependency you specify. (It might interpret the string as an array and look for modules j, q, etc. I'm not sure about this...) So it loads Bootstrap irrespective of whether jQuery is loaded.

It works when you use a CDN probably because of a timing difference: it takes long enough to fetch from the CND that jQuery is loaded before Bootstrap loads. When you do it locally, Boostrap loads too fast and jQuery is not loaded yet. At any rate, using the array as I show above should solve the problem.

0
votes

thanks for your help, When I downloaded RequireJS i never realized what version I was using.
I thought I had the latest but I was using 1.0.8, I upgraded and now I have 2.1.14, that solved the problem. There's no need of using an export on the shim object as many entries say

shim: { 
    "bootstrap": {
        deps : ['jquery'], // Use an array even with a single dependency.  
        export : '$.fn.modal'
    } 
}

Thanks for your help :D