don_Bigote
don_Bigote

Reputation: 947

How to make Select2 work with rails 6 app in production?

I have a Rails 6 app. I am using the select2 plugin. It works in development, but it does not work in production (Heroku).

I ran

yarn add select2

Here is application.js

require("@rails/ujs").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
require("chartkick")
require("chart.js")
require("custom/scripts")
require("custom/programs")

Here is package.json

{
  "name": "case_reporter",
  "private": true,
  "dependencies": {
    "@primer/css": "^14.2.0",
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "chart.js": "^2.9.3",
    "chartkick": "^3.2.0",
    "jquery": "^3.4.1",
    "select2": "^4.0.13",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}

Here is my select js in custom/programs.js

import $ from 'jquery'
import 'select2'
import 'select2/dist/css/select2.css'

window.addEventListener('DOMContentLoaded', () => {
  $('.js-source-programs').select2()
})

here is environment.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

module.exports = environment

In my html I have:

= f.collection_select :program_type_id, ProgramType.all, :id, :name, { class: 'form-select js-source-programs' }

It is working in development without any problems.

In production on Heroku, it is not working. AND there are no errors in the console.

What could cause this to not work in production?

Here is the head

  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %meta{:content => "width=device-width, initial-scale=1, shrink-to-fit=no", :name => "viewport"}/
    %title CS-DM
    = csrf_meta_tags
    = csp_meta_tag
    = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'

    %script{:src => "https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.js"}
    %link{:href => "https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.css", :rel => "stylesheet"}/

Upvotes: 1

Views: 1926

Answers (1)

Alex R
Alex R

Reputation: 11

I had this issue - this answer resolved it for me: https://stackoverflow.com/a/58007621/4741698

The issue is including CSS in application.js without adding <%= stylesheet_pack_tag 'application.js', 'data-turbolinks-track': 'reload' %>. So either add the stylesheet_pack_tag, or move the CSS to a file that is already included with a stylesheet_pack_tag.

Upvotes: 1

Related Questions