How can I using select2 with webpack?
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.
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
- Switch on
$.fn.select2.defaults.set('debug',true);
when diagnosing language issues. - Avoid strange language defaults by adding
$("html").removeAttr("lang");
to your app.
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();
});
You can simply do like this :
import $ from 'jquery';
import 'select2';
$('selector').select2(); //selector can be className, ID, tag name , attributeName , etc ...