简体   繁体   中英

Browserify jQuery is not defined?

So I know how to manually fix this but it's annoying!

I included bootstrap dropdown.js and at the end of the function is

}(jQuery);

Inside my shim I set jquery as a dependency

'bootstrap': {
    "exports": 'bootstrap',
    "depends": {
        "jquery": '$'
    }
},

It seems like this is the only way to use $ , but since the dropdown has jQuery at the end the console shows

ReferenceError: jQuery is not defined

}(jQuery);

Changing it to }($); works.

So my question is does anyone have any idea to better do this without manually doing it, or is manually editing the script the best?

You can use global.jQuery = require("jquery")

This is my shim :

},
"plugin": {
    "exports": "plugin",
    "depends": [
        "jquery: $",
        "bootstrap: bootstrap"
    ]
}

and inside of plugin.js :

var $ = require('jquery')(window);
global.jQuery = require("jquery");
var bootstrap = require('bootstrap');
var plugin = require('plugin');

plugin();

it solve my problem. Hope it helps. :)

Shim
"./node_modules/jquery/dist/jquery.js": { "exports": "$" }

requiring
var jQuery = $ = require('$');

This should cover both plugins that use

(function($){
 $.fn.function_name = function(x){};
})($);

as well as

(function($){
  $.fn.function_name = function(x){};
})(jQuery);

I don't think my solution is anywhere near optimal or ideal and it doesn't answer my question but if anyone has this issue just do it this way, you can get it working possibly as a temporary solution to get things going without stagnating on your project.

Most if not all jQuery plugins are written with a self invoking function like this.

(function($){
  $.fn.function_name = function(x){};

})(jQuery);

I simply went into the plugin itself and changed (jQuery) to ($)

(function($){
  $.fn.function_name = function(x){};

})($);

If you're still having problems, make sure you have a shim defined in your package.json file and you are including the jQuery plugin with a require statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM