How to require select2 with webpacker/Rails?

Hello,

I’ve been using select2 via sprockets/Rails asset pipeline. I had downloaded select.js and put it under verndor/assets/javascripts. Recently, I started migrating a Rails application to using the webpacker gem. I stumbled upon a difficulty, where I can’t import/require or in any way include it. So here is my setup:

I’ve migrated jQuery via the following steps:

  1. yarn add jquery
  2. Added to my environment.js file (this is the configuration file, that webpacker uses to configure webpack):
const webpack = require('webpack');

environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery'
}));

I can confirm, that now I have jquery globally available, without needing to do import $ from 'jqyery'.

Now comes the problem with select2. I ran yarn add select2, however I am not sure what I need to include into my js file in order to be able to use select2 with an input like so:

$('select').select2();

I tried all kinds of imports like:

import select2 from 'select2';
import select2 from 'select2/dist/js/select2.js';
import select2 from '../../../node_modules/select2/dist/js/select2.js';
import 'select2/dist/js/select2.js'

and many others, but none of these seem to work. Please, advise. Thank you.

Cheers,
Alex

Did you manage to solve this problem Alex? I’m facing the same too.

Hey @BKSpurgeon, no, I haven’t had the change to work on this.

For me, the following finally worked with Rails 6 and webpacker:

  • Do not configure jquery as externals in environment.js
  • yarn add jquery
  • Make sure that you are not loading jquery from Sprockets. If you do, you will load jquery twice (once via Sprockets, once via webpacker) and select2 will probably be loaded into the wrong one.
  • In packs/application.js:
import $ from 'jquery';
import select2 from 'select2';
import 'select2/dist/css/select2.css';

$(document).ready(function() {
  $('select').select2();
});
1 Like