How can I using select2 with webpack?

bnqtoan picture bnqtoan · Jul 20, 2016 · Viewed 25.6k times · Source

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!

Answer

Everettss picture Everettss · Jul 20, 2016

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();
});