importjquery-select2vite

Importing Select2 & Laravel Vite


I'm trying to use select2 in my Laravel 10 project, which is using Vite. I kept getting the error

    Uncaught TypeError: $(...).select2 is not a function

My question:

What is the correct way to import select2 in Vite (without having to use a Vite config alias)? What am I doing wrong?

I've run npm i select2 (from my package.json)

    "select2": "^4.1.0-rc.0",
    "vite": "^4.0.0"

I've tried a bunch of different ways of importing but landed on

  1. updating my vite.config.js file (simplified for example)

     import { defineConfig } from 'vite';
     import laravel from 'laravel-vite-plugin';
     import path from 'path';
    
     export default defineConfig({
         plugins: [
             laravel({
                 input: ['resources/sass/app.scss', 'resources/js/app.js'],
                 refresh: true,
             }),
         ],
         resolve: {
             alias: {
                 'select2': 'node_modules/select2/dist/js/select2.full.min.js',
    
             }
         },
     });
    
  2. using the following in my app.js

     import 'select2';
     import '../../node_modules/select2/dist/css/select2.css';
    

The weird thing is

  1. select2 is working
  2. I get a console log error: Failed to load url /@fs/node_modules/select2/dist/js/select2.full.min.js (resolved id: /node_modules/select2/dist/js/select2.full.min.js? [...]

Solution

  • To get it working without alias, follow these steps:

    1. Install jquery and select2:
    npm i jquery select2 --save-dev
    
    1. Edit bootstrap.js for referencing jquery and select2
    // import jquery and select2
    import $ from "jquery";
    import select2 from 'select2';
    window.$ = $; // <-- jquery must be set
    select2(); // <-- select2 must be called
    
    1. Import select2 CSS in app.js
    //-- Select2
    import "/node_modules/select2/dist/css/select2.css";
    //--
    import '../css/app.css';
    // ...
    

    Now you can use it in your components:

    $('.js-example-basic-single').select2();
    

    select2 rendering example