NodeJS with webpack jQuery.Deferred exception: o(...).select2 is not a function TypeError: o(...).select2 is not a function

NodeJS with webpack jQuery.Deferred exception: o(...).select2 is not a function TypeError: o(...).select2 is not a function

我正在修改我的应用程序以通过 gulp 使用 nodejs 和 browserify 来生成一个缩小的 js。
我已经从手动加载依赖项和手动更新切换到使用 npm 安装它们。

一切顺利,但当我想安装 select2 时,它开始到处抛出错误。当我为 npm required() 文件移动我删除的手动更新文件时。

jquery.js:3841 jQuery.Deferred exception: o(...).select2 is not a function TypeError: o(...).select2 is not a function
at i.init (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:5612)
at i.sysInit (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:108153)
at i (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:106602)
at new i (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:5333)
at HTMLSelectElement. (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:108496)
at Function.each (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:200628)
at _.fn.init.each (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:199273)
at _.fn.init.d.fn.(anonymous function) [as FormDropdownHandler] (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:108384)
at HTMLDocument. (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:108696)
at HTMLDocument.dispatch (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:240241) undefined

dropdown.module.js:53 Uncaught TypeError: o(...).select2 is not a function
at i.init (dropdown.module.js:53)
at i.sysInit (oc.foundation.base.js:157)
at i (oc.foundation.base.js:20)
at new i (dropdown.module.js:19)
at HTMLSelectElement. (oc.foundation.base.js:191)
at Function.each (jquery.js:367)
at _.fn.init.each (jquery.js:202)
at _.fn.init.d.fn.(/anonymous function) [as FormDropdownHandler] (https://www.example.com/newstyle/js/closure.js?time=1559747711:1:108384)
at HTMLDocument. (oc.foundation.base.js:213)
at HTMLDocument.dispatch (jquery.js:5237)

我使用的代码是:

<select name="pickup_point">
    <option value="1" >all work</option>
    <option value="4" >no play</option>
    <option value="5" >dull boy</option>
</select>

和 javascript:

$ = require('jquery');
require('select2');
$(document).ready(function(){
    $('select').select2();
});

当我在 index.js 文件中需要 select2 时,如何让它工作?

我花了一些时间来拼凑这里出了什么问题。

归结为 Select2 使用它自己的加载器和工厂函数来初始化自身,默认情况下不会调用它。需要手动调用。

如果您有一个 window 对象并已将 jQuery 注册到 window 对象,您可以在主函数中按如下方式调用 Select2 一次 javascript 文件:

window.$ = window.jQuery = require('jquery);
require('select2')();

或者如果你更喜欢变量而不是直接调用 require 函数:

window.$ = window.jQuery = require('jquery);
var select2Initialisator = require('select2');
select2Initialisator();

如果你喜欢使用作用域或不同版本的 jQuery,你也可以将你希望注册 select2 的 jQuery 实例传递给 select2 工厂构造函数,如下所示

 var jQuery = require('jquery');
 require('select2')(jQuery);