Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use select2 with webpack?

I've downloaded select2 as node module by:

npm install select2

and included it in my app.js:

require('select2')($);


When I run webpack there are no errors, but when I open the app I get:
Uncaught TypeError: Object.defineProperty called on non-object(…)

coming from select2.js:

S2.define('select2/core',[
  'jquery',
  './options',
  './utils',
  './keys'
], function ($, Options, Utils, KEYS) {
(...)
}

Does it happen because module wrapper for select2 works only with AMD and is incompatible with CommonJS?

like image 642
van_folmert Avatar asked Dec 23 '16 09:12

van_folmert


People also ask

How do I add Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change');

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?

This POC is intended to illustrate Select2, a JQuery Plugin which is used as a replacement for select box with support for searching, tagging, remote data sets, infinite scrolling and many other highly used options and contains event handling.

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.


2 Answers

Where do you see this is how to use select2? As far as I can see from glancing at the project, you need jquery installed as a dep but then it will be automatically required.

Looking at the signature of the exported function it looks like it might take a jQuery element and options: https://github.com/select2/select2/blob/master/dist/js/select2.js#L5052

However after importing it, it should just be attached to jQuery as a plugin, so I'd think that $('.some-element').select2([options]); would also work.

So did you simply try require('select2') (and npm i jquery --save if you haven't)?

like image 70
Dominic Avatar answered Sep 22 '22 23:09

Dominic


if someone looking for this now just doing require('select') is not going to attache it jquery you have to require('select2')(); then you can call

$(document).ready(()=>{
  $('.select2').select2()
})

then It will work. now I have tested this with electron js. it's working!

in my doc, this is how I import everything first jquery then select2

  window.$ = window.jQuery = require("jquery");
  require('select2')();
like image 38
Thalinda Bandara Avatar answered Sep 21 '22 23:09

Thalinda Bandara