select2: [BUG] `Uncaught TypeError: $(...).select2 is not a function` with `4.1.0-rc.0 `

I just wasted an hour because npm installed version 4.1.0-rc.0. With 4.0.13 everything works as expected.

I’m using webpack and imported it with import 'select2'

When running

$('.select2').select2()

I get the error Uncaught TypeError: $(...).select2 is not a function

I’m not sure if it’s related to using webpack or because I’m using jQuery v3.6.0 (the release notes say The minimum jQuery version supported is the latest version in the 1.x, 2.x, and 3.x series). But in either way it definitely should either work or output a better error message.

Additional Notes

I had to add the following webpack config (using laravel-mix) because I’m unfortunately have to use WordPress and jQuery is loaded via an own script tag, not included in the webpack bundle:

mix.webpackConfig({
	externals: {
		$: 'jQuery',
		jquery: 'jQuery',
	}
})

without this config select2 won’t attach to jQuery.fn

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 1
  • Comments: 20 (1 by maintainers)

Most upvoted comments

This works:

import select2 from 'select2';
select2();

or

import("select2").then(m => m.default());

and later

$(el).select2()

dont use npm crap

I use vite, it seems no versions can work.

I had to do the following to initialise select2 properly:

import select2 from 'select2';
select2($);

I include and setup jQuery like this:

import jquery from 'jquery';

window.jQuery = jquery;
window.$ = jquery;

The problem with this is that it works with npm run dev but not with npm run build when it throws an error 'default' is not exported by node_modules/select2/dist/js/select2.js when using Vite

This is not isolated to webpack. I can confirm this error occurs when using 4.1.0-rc.0 from CDN’s also.

This works:

import select2 from 'select2';
select2();

or

import("select2").then(m => m.default());

and later

$(el).select2()

It really Works for me

This works:

import select2 from 'select2';
select2();

or

import("select2").then(m => m.default());

and later

$(el).select2()

Saved a lot of my time and energy!! Thank you so much!!