I'm stuck trying to get StimulusReflex working in my existing Rails 7.0.5 project with importmaps.
I installed:
gem "stimulus_reflex", "= 3.5.0.rc3"
importmaps.rb
# Pin npm packages by running ./bin/importmap
pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "https://ga.jspm.io/npm:@hotwired/[email protected]/dist/stimulus.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
puts "Import map loaded"
pin "stimulus_reflex", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus_reflex.js"
pin "@rails/actioncable", to: "https://ga.jspm.io/npm:@rails/[email protected]/app/assets/javascripts/actioncable.esm.js"
pin "cable_ready", to: "https://ga.jspm.io/npm:[email protected]/dist/cable_ready.js"
pin "morphdom", to: "https://ga.jspm.io/npm:[email protected]/dist/morphdom.js"
pin "stimulus", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus.js"
pin "@rails/actioncable", to: "actioncable.esm.js"
pin_all_from "app/javascript/channels", under: "channels"
javascript/controllers/index.js
import { Application } from 'stimulus'
import StimulusReflex from 'stimulus_reflex'
import consumer from '../channels/consumer'
const application = Application.start()
application.consumer = consumer
StimulusReflex.initialize(application, { isolate: true })
// Eager load all controllers defined in the import map under controllers/**/*_controller
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
I set up a simple reflex to test reflexes/example2_reflex.rb
# frozen_string_literal: true
class Example2Reflex < ApplicationReflex
def test
puts "test"
end
end
I have no errors in my browser console. Terminal console shows:
StimulusReflex::Channel is transmitting the subscription confirmation
StimulusReflex::Channel is streaming from StimulusReflex::Channel
When I click my test button which calls Example2#test in my terminal console I get:
StimulusReflex::Channel#receive({"attrs"=>{"data-reflex"=>"click->Example2#test", "data-controller"=>"stimulus-reflex", "data-action"=>"click->stimulus-reflex#__perform".....
But then in red:
Reflex Example2#test failed: uninitialized constant ApplicationReflex
Which is kind of a big deal if Example2Reflex is not inheriting from ApplicationReflex!
Can someone help me?
I actually got it working a minute after I posted my question...
I did not add an application_reflex.rb file into my reflexes folder.
It works now with importmaps! If anyone does have any improvements to the setup, please let me know.