Using Symfony 4 and Webpack Encore , I can't get Select2 to work.
I'm using select2@4.0.3
and importing it this way in app.js
:
import $ from 'jquery';
import 'bootstrap';
import 'select2';
I also tried to use
Encore.autoProvidejQuery()
in webpack.config.js
, then taking care of commenting the
import $ from 'jquery';
line in app.js
so that jquery is not imported twice.
I tried everything I could find in other answsers like:
import select2 form 'select2';
$(() => {
$('.select2-enable').select2();
});
or
select2($);
Almost all my attempts result in the same error:
TypeError: $(...).select2 is not a function
EDIT:
Working now. Everytime I made a change in app.js
(and rebuilt) I used the firefox devtool console to check if it was working but I always got the
not a function
error even though the problem was solved and select2 was working.
Is this because I'm using Webpack that the browser console doesn't recognize the select2()
function anymore?
First install it using yarn
:
yarn add select2
Then use it with require
instead of import
:
require('select2')
at your app.js
file.
It works the same using require or import.
Babel converts import and export declaration to CommonJS (require) which lets you load modules dynamically.
So, despite of them looking the same, try to always use require.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.