Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I using select2 with webpack?

I'm using webpack to manage all my assets, when I use this code to require select2 (https://github.com/select2/select2) I got the error

$(...).select2 is not function.

require.ensure(['./vendors/select2'],function (require) {     require('./site'); }); 
// site.js (function ($) {     $(document).ready(function () {         $(".js-1example-basic-single").select2();     }); })(jQuery); 

I think there is something wrong with module export. I tried many search but no hope.

Anyone please tell me what to do, It took me about 10 hours.

Thank you!

like image 306
bnqtoan Avatar asked Jul 20 '16 05:07

bnqtoan


People also ask

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.

Is Select2 a plugin?

Select2 is a powerful JQuery plugin that is designed to add more power to the traditional <select> box that is displayed on the browser. It supports searching, remote data-sets via AJAX, mult-selects, pagination, grouping, custom rendering and so much more.

How does Select2 search work?

When users filter down the results by entering search terms into the search box, Select2 uses an internal "matcher" to match search terms to results. You may customize the way that Select2 matches search terms by specifying a callback for the matcher configuration option.

Is Select2 JQuery?

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.


2 Answers

You can run select2 in this way:

import $ from 'jquery'; import 'select2';                       // globally assign select2 fn to $ element import 'select2/dist/css/select2.css';  // optional if you have css loader  $(() => {   $('.select2-enable').select2(); }); 
like image 159
Everettss Avatar answered Nov 19 '22 09:11

Everettss


For anyone using Parcel bundler to load select2, simply importing it didn't work.

I had to initialize it as follows instead:

//Import import $ from 'jquery'; import select2 from 'select2';  //Hook up select2 to jQuery select2($);  //...later $(`select`).select2(); 

Without the hookup call and passing jQuery into the function, it wouldn't bind and result in a $(...).select2 is not function. error.

like image 21
Adam Reis Avatar answered Nov 19 '22 08:11

Adam Reis