Reputation: 435
I have a Laravel 9 app. I am trying to get select2
to work however, when I do npm run build
I get the error:
RollupError: "default" is not exported by "node_modules/select2/dist/js/select2.js", imported by "resources/js/app.js".
I installed select2
using the following:
npm install select2 --save-dev
Then I added the following lines in my app.js
file after the jquery import:
import select2 from "select2"
select2()
Everything seems to be fine in dev mode. However, as soon as I try to build it, I get the error mentioned above. Does anyone know how to fix this?
Upvotes: 5
Views: 2072
Reputation: 1
As select2 does not support ES6 we can use import * as select2 from 'select2' in app.js
I'm using Laravel 9, Vite and Sass; this is my full working config in app.js to import jQuery and select2:
import $ from 'jquery';
import jQuery from 'jquery';
window.jQuery = jQuery;
window.$ = $;
import * as select2 from 'select2';
select2($, jQuery);
This is my vite.config.js file:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import inject from "@rollup/plugin-inject";
export default defineConfig({
plugins: [
inject({
$: 'jquery',
jQuery: 'jquery',
}),
laravel({input: ['resources/sass/app.scss', 'resources/js/app.js',], refresh: true}),
]
});
Finally remember to add type="module" to any script elements in your blade templates if you are calling jQuery there.
Some of this configuration may not be needed for select2 to work but I have other packages that require jQuery and so I have included all configuration that works for me.
Upvotes: 0
Reputation: 38670
As I know, select2
is a jQuery plugin and does not use ES6
modules. If no ES6
means No support for export default
To use this,
Import it with a jQuery structure.
npm install jquery --save
In code
import $ from 'jquery';
window.jQuery = $;
window.$ = $;
import 'select2'; // Modifies the global jQuery object.
$('select').select2();
can try this too How can I using select2 with webpack?
If you have CSS, you can add in main CSS or SASS(ex: app.scss
)
@import "~select2/dist/css/select2.min.css";
Finally, run
npm run build
In case you need CDN Using Select2 from a CDN
Upvotes: 1
Reputation: 1
Try this
import $ from 'jquery';
import 'select2';
// Optional: Import select2 CSS if needed import 'select2/dist/css/select2.min.css';
// Initialize select2 $(document).ready(function() { $('select').select2() })
than
npm run dev
Upvotes: -2