uxsolutions / bootstrap-datepicker

A datepicker for twitter bootstrap (@twbs)
Apache License 2.0
12.68k stars 6.06k forks source link

Issues with browserify and global jQuery #2362

Open ollyollyollyltd opened 6 years ago

ollyollyollyltd commented 6 years ago

Related to #1761 but that hasn't been touched since Nov 2016...

When using Browserify to bundle my code the datepicker() function does not attach to the global jQuery object.

window.jQuery = require('jquery');
require('bootstrap-datepicker`);

jQuery("#input").datepicker()

// Error: jQuery(...).datepicker is not a function

I believe this is due to the way that datepicker implements the factory function:

// bootstrap-datepicker.js:7
(function(factory){
    if (typeof define === "function" && define.amd) {
        define(["jquery"], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        factory(jQuery);
    }
}(function($, undefined){
    ...
}

As a workaround I have edited line 11 to attempt to use window.jQuery, falling back to require('jQuery') if it is not found:

// bootstrap-datepicker.js:7
(function(factory){
    if (typeof define === "function" && define.amd) {
        define(["jquery"], factory);
    } else if (typeof exports === 'object') {
        factory(window.jQuery || require('jquery')); // <---- Changed
    } else {
        factory(jQuery);
    }
}(function($, undefined){
    ...
}

Obviously this is not ideal as I have had to take the code out of NPM management to prevent it being overwritten on update. Is there a better way to handle this?

jdnierth commented 5 years ago

I can confirm that the above workaround also works for a similar case: I was using this Plugin in combination with requireJS where the key to the jquery library was set to 'jquery' and exported in a shim to '$'. The case I required was the first one since requireJS is using the AMD pattern which relies on 'define'.

// node_modules/bootstrap-datepicker/dist/js/bootstrap-datepicker.js // Datepicker for Bootstrap v1.8.0 (https://github.com/uxsolutions/bootstrap-datepicker)

if (typeof define === 'function' && define.amd) {

  define(['jquery'], factory(window.jQuery || require('jquery'))); // AMENDED

} else if (typeof exports === 'object') {

   factory(window.jQuery || require('jquery')); // AMENDED

} else {

   factory(window.jQuery || require('jquery')); // AMENDED

}

Without this amend the console would throw an error 't.fn.datepicker is undefined' once initializing the datepicker.