31

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!

bnqtoan
  • 649
  • 1
  • 7
  • 13

5 Answers5

59

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();
});
Everettss
  • 13,024
  • 7
  • 63
  • 89
  • @bnqtoan I've included properly working link in webpackbin. – Everettss Jul 21 '16 at 05:26
  • I'm really appreciate your help! @Everettss – bnqtoan Aug 04 '16 at 16:28
  • @Everettss link is dead. – Sizzling Code Aug 20 '17 at 12:25
  • @SizzlingCode I have just created new webpackbin (and updated answer). – Everettss Aug 20 '17 at 12:42
  • 2
    @does this require that jquery be bundled? I'm loading my bundle into a site that already has jquery installed. So it's not part of my bundle. I tried `import select2` in my loader.js file but I still get `select2 is not a function` – Batman Sep 22 '18 at 23:07
  • @Batman See the Webpack `externals` configuration option. `externals: { jquery: "jQuery" }` worked for me. This instructs Webpack to exclude jquery from your bundle and imports will still work. – Gili Sep 08 '19 at 04:54
9

For anyone using Parcel bundler to load select2, simply importing it didn't work.

I had to initialize it as follows instead:

//Import
import $ from 'jquery';
import select2 from 'select2';

//Hook up select2 to jQuery
select2($);

//...later
$(`select`).select2();

Without the hookup call and passing jQuery into the function, it wouldn't bind and result in a $(...).select2 is not function. error.

Adam Reis
  • 3,106
  • 35
  • 27
  • Thanks, in my case in my app(Meteor) with many packages, i must initialize like this : select2(window,$); – Dayd Jan 29 '21 at 10:55
5

Load the src version of Select2

Sean Larkin, one of the webpack developers says:

Most modules link the dist version in the main field of their package.json. While this is useful for most developers, for webpack it is better to alias the src version because this way webpack is able to optimize dependencies better...1

Following this advice, I prefer to require files under the src folder:

require("select2/src/js/jquery.select2.js");
require('select2/src/scss/core.scss');

Load language files statically

You'll then find there are various language-related hurdles to overcome. As soon as you insert $(".dropdown").select2() into your code, you'll see Uncaught Error: Cannot find module './i18n/en'. This is because the dynamic require designed for RequireJS is not working. It comes from the loadPath function in translation.js:

if (!(path in Translation._cache)) {
    var translations = require(path);
    Translation._cache[path] = translations;
}

In webpack parlance this is called a 'require expression'. My solution is to avoid ever reaching that line by priming the cache first. In my app code I put:

const EnglishTranslation=require("select2/src/js/select2/i18n/en");
const Translation=require("select2/src/js/select2/translation");
Translation._cache["./i18n/en"]=EnglishTranslation;
Translation._cache["en"]=EnglishTranslation;

You will need to do this for all the languages you wish to use. Then you can use the language features as documented, including $.fn.select2.defaults.set('language',"en") or language: en during initialisation. Overrides like language: { noResults: function() { return "abc"; } } work also.

Disable the contextless require

The above instructions give you a working select2, but Webpack will be complaining, Critical dependency: the request of a dependency is an expression. This means, "webpack needs to include all files inside the current folder and all files in child folders"2, which would be everything under select2/src/js/select2!

I found I could use imports-loader to disable the require() in the translation module completely, whilst leaving the define() call intact, so that it could still do its exports. Here's an excerpt from my webpack.config.js:

module: {
    rules: [
        {
            test: /select2\/src\/js\/select2\/translation\.js$/,
            use: {
            loader: "imports-loader",
            options: "require=>false"
        }
     ]
}

Writing Custom Adapters

You can use webpack to require() various components to write your own data adapters. The select2 adapter documentation assumes you will use something like the supplied Almond loader (e.g. $.fn.select2.amd.require), so it took me a while to realise I could do this kind of thing:

var Utils = require("select2/src/js/select2/utils");
var ArrayAdapter = require("select2/src/js/select2/data/array");

Hints

  1. Switch on $.fn.select2.defaults.set('debug',true); when diagnosing language issues.
  2. Avoid strange language defaults by adding $("html").removeAttr("lang"); to your app.
rohanc
  • 385
  • 3
  • 8
1

You can simply do like this :

import $ from 'jquery';
import 'select2';


$('selector').select2(); //selector can be className, ID, tag name , attributeName , etc ...
MUSTAPHA GHLISSI
  • 792
  • 6
  • 11
0

Tried all above solutions but the only way I'v managed to use select2 with webpack and rails6 was to add script loaded to the package and use it like:

import 'select2';
import 'script-loader!select2/dist/js/select2.js';
import 'select2/dist/css/select2.css';

Artur79
  • 10,574
  • 1
  • 20
  • 22