Use select2 version 4.0 with NPM and browserify

3.5k views Asked by At

I am trying to use select2 version 4.0 in an ampersand-js app - as such that means I am using npm and browserify.

Unfortunately I cannot get select2 to load up.

the js file is being loaded up without error, since I can add a few console.log statements in relevant places and see them output,

but when I try to use select2 I'm getting told it's not defined.

Uncaught TypeError: $(...).select2 is not a function

Here's what I'm trying to do.

var $ = require('jquery');
require('Select2');

$('select').select2();

I have a feeling the issue comes from this line in the select2.js https://github.com/select2/select2/blob/4.0.0/dist/js/select2.js#L14

Specifically that it calls factory(require('jquery')); hence I believe that select2 is loading into a copy of jQuery that is then thrown away?

I found this issue which sounds like it's about the same thing, except I cannot get it to work either: npm browserify version of jquery-select2 version 4.x

1

There are 1 answers

1
Hailwood On BEST ANSWER

So my train of thought was almost correct - it was loading select2 onto the wrong copy of jQuery.

There was two versions of jQuery being loaded.

In my package.json I had listed jQuery as a dependancy, however I wa also loading in the bower version of jQuery via the browser: {"jquery: "./bower_components/.../jquery.js"} key.

It seems that anything outside of the node_modules directory likely uses the "browser" defined module, whereas anything inside the node_modules directory will use the npm loaded module.

Basically, if something similar happens double check that you're not loading in two copies of libraryX.