Reputation: 807
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
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',
}
},
});
using the following in my app.js
import 'select2';
import '../../node_modules/select2/dist/css/select2.css';
The weird thing is
select2
is working/@fs/node_modules/select2/dist/js/select2.full.min.js (resolved id: /node_modules/select2/dist/js/select2.full.min.js? [...]
Upvotes: 3
Views: 2048
Reputation: 5714
To get it working without alias, follow these steps:
npm i jquery select2 --save-dev
// import jquery and select2
import $ from "jquery";
import select2 from 'select2';
window.$ = $; // <-- jquery must be set
select2(); // <-- select2 must be called
//-- 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();
Upvotes: 3