How to use select2 with webpack?
Asked Answered
D

2

7

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?

Dees answered 23/12, 2016 at 9:54 Comment(0)
N
2

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)?

Nertie answered 11/1, 2017 at 16:40 Comment(1)
Of course I had jquery, I thought it was too obvious to mention that. The problem was that some jquery plugins are wrapped in UMD which does some quirky checks if I use AMD, CommonJS or none, and this check breaks in Webpack, because Webpack supports both, so UMD wrapper assumes I use AMD even though I use commonJS. There is a hacky workaround for this in accepted answer at #4.Dees
S
1

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')();
Seidel answered 1/12, 2020 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.