How to require select2 with webpacker/Rails?


#1

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