YY1's avatar
Level 1

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

0 likes
7 replies
MichielE's avatar

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?

Merklin's avatar

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

YY1's avatar
Level 1

@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.

bouboo's avatar

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

2 likes
silvior92's avatar

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 or to participate in this conversation.