Problem with Select2, Laravel 10 and Vite Hello, can you help me including Select2 into Laravel 10? I am using Vite
This is my app.js
import $ from 'jquery';
window.$ = window.jQuery = $;
window.select2 = require('select2');
import * as bootstrap from 'bootstrap';
window.bootstrap = bootstrap;
and i get this error
Uncaught TypeError: $(...).select2 is not a function
Is Select2 loaded correctly? It seems to me that the problem is that Select2 isn't properly loaded. What happens if you load Select2 after Bootstrap?
There are a few known bugs regarding Bootstrap and select2. Also, adding the whatever custom js library via vite way may lead to unpredicted behaviour/conflicts.
To solve this, load select2 js separately:
<body>
...
<script src="{{ asset('storage/assets/js/select2.min.js') }}"></script>
</body>
Also, if select2 is loaded in a bootstrap modal and its search is not working before the end body tag add this:
<script>
jQuery( document ).ready(function( $ ) {
$('#select_id').select2({
dropdownParent: $('#modal_id'),
});
});
</script>
https://select2.org/troubleshooting/common-problems
@Merklin No it's not loaded in Bootstrap 5.3 modal i want to include it globally in my app.js so every file will have access to it but doesnt work.
This worked for me
In your app.js
import jQuery from 'jquery';
import select2 from "select2"
select2();
window.$ = jQuery;
In your vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: [
...
'resources/js/app.js',
...
],
refresh: true,
}),
],
resolve : {
alias: {
'$':'jQuery',
}
},
});
Hope it'll help
Thx @bouboo . This solution still work on laravel 11
This doesn't work for me. It works with npm run dev but fails with npm run build with the error
error during build:
resources/js/bootstrap.js (8:7): "default" is not exported by "node_modules/select2/dist/js/select2.js", imported by "resources/js/bootstrap.js".
file: /resources/js/bootstrap.js:8:7
Any help hare? Thanks..!!
Please sign in or create an account to participate in this conversation.