I'm in the process of migrating a Rails 5.1.5 project, which uses CoffeeScript, from using sprockets to using webpacker. The project also uses select2.js
. With sprockets, I did the following:
- Install
jquery-rails
(jQuery is a dependency forselect2
). - Put
select2.js
code invendor/assets/javscripts
. In
application.js.coffee
, add:#= require select2
After that I was able to use select2 to in my application.js.coffee
file:
$(document).on 'turbolinks:load' ->
$('select').select2
So far I've described the pretty standard way of including/using javascript libraries with sprockets.
However, with webpacker I can't make select2 work and I'm not sure why. I have two hypothesis:
- I'm not importing/requiring it properly;
- it doesn't find jQuery at some point of the load process;
So for jQuery, I did the following:
yarn add jquery
included in my
environment.js
:const webpack = require('webpack'); environment.plugins.append('Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }));
I've removed the jquery-rails
gem, as well as #= require 'jquery'
and tested that jquery works, so I guess I have correctly included it. However, I tried several ways of importing select2
(using es6 imports) and none of them worked. I tried:
import select2 from 'select2';
import select2 from 'select2/dist/js/select2'
import select2 from 'select2/dist/js/select2.js'
import 'select2/dist/js/select2.js'
I even tried to import it from the old vendor location
by writing inside app/javascript/pack/application.js.coffee
:
import '../../../vendor/assets/javascripts/select2'
I can confirm that the file contents is imported, as I put a console.log within the select2 file under node_modules/select2/dist/js/select.js
and it did get printed. However, I also get the error TypeError: $(...).select2 is not a function
when I execute $('select').select2()
in the browser's dev tool console.
What am I missing or doing wrong?
P.S. I can provide much more info, but I didn't want my question to get any more bloated. P.P.S. With my modest JS knowledge, I looked at the source code but couldn't recognize what exactly they are exporting and how am I supposed to import it.