简体   繁体   English

使用CommonJS加载jQuery插件

[英]Loading a jQuery plugin with CommonJS

I'm trying to use Webpack to bring in JS modules, including jQuery and a jQuery plugin. 我正在尝试使用Webpack引入JS模块,包括jQuery和jQuery插件。 I can load jQuery in without any problem, but when I try to load in a plugin to use along with it, I get a jQuery is not defined error in my browser console. 我可以毫无问题地加载jQuery,但是当我尝试加载与之一起使用的插件时,在浏览器控制台中出现jQuery is not defined错误。 I'm pretty new to Common JS and Webpack so any help would be really appreciated. 我是Common JS和Webpack的新手,所以我们将不胜感激。

Here's my code so far: 到目前为止,这是我的代码:

var $ = require('../../../../../bower_components/jquery/dist/jquery.js');
require('../../../../../bower_components/jquery.uniform/jquery.uniform.js');

module.exports = function(){
    function init(){
        $('select, checkbox').uniform();
    }

    return {
        init: init
    };
}();

It's at the end of the jquery.uniform.js file that I get the error I mentioned above, because it references jQuery , which for some reason is not yet defined. jquery.uniform.js文件的末尾,我得到了上面提到的错误,因为它引用了jQuery ,由于某种原因,它尚未定义。

(function (wind, $, undef) {
    ...
    ...
}(this, jQuery));

Any ideas how to make this work? 任何想法如何使这项工作? Or am I doing this completely wrong? 还是我这样做完全错误?

I think you may want to give it a go through npm. 我认为您可能想通过npm。 Set up a package.json dep like this: 像这样设置package.json dep:

"uniform": "pixelmatrix/uniform#v2.1.2",

Also make sure jquery is within your project (ie. npm i jquery --save ). 还要确保jquery在您的项目中(即npm i jquery --save )。

After these steps you could try an import like this: 完成这些步骤后,您可以尝试执行以下导入操作:

var uniform = require('imports?$=jquery!uniform/jquery.uniform');

You should be able to push the nasty looking import to Webpack configuration provided this works. 如果可行,您应该可以将看上去讨厌的导入推送到Webpack配置。 I hope this helps! 我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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