How to import controllers and turbo-rails with sprockets

Hi community,

I want to implement StimulusJS into my Rails 7 application which is still using sprockets.
The javascript/application.js file is using using Sprockets directives like

//= require jquery3
//= require popper
//= require bootstrap-sprockets

However, Stimulus requires me to import the turbo-rails and controllers with

// import "@hotwired/turbo-rails"
// import "controllers"

As a result, these modules are not properly imported in the application.js file and the controllers do not work.

Please let me know if anyone has idea on how I can import these modules using Sprockets! Any help would be appreciated!.Thank you!

I have:

importmap.rb

pin ‘application’
pin ‘@hotwired/turbo-rails’, to: ‘turbo.min.js’
pin ‘@hotwired/stimulus’, to: ‘stimulus.min.js’
pin ‘@hotwired/stimulus-loading’, to: ‘stimulus-loading.js’
pin_all_from ‘app/javascript/controllers’, under: ‘controllers’
pin ‘popper’, to: ‘popper.js’, preload: true

application.js

import “@hotwired/turbo-rails”
import “controllers”
import “popper”
and more…

Hope that helps…
Werner

Hi Werner, thanks for your reply.

As I am using sprockets, the application.js needs me to add dependencies in sprockets directives //=require , so I cannot import the dependencies with ES6 import “@hotwired/turbo-rails” import “controllers” here.

You can import it as follows:

//= require @hotwired/turbo/dist/turbo.es2017-umd.js
//= require @hotwired/stimulus/dist/stimulus.umd.js

Check that in your package.json you have “@hotwired/stimulus” and “@hotwired/turbo-rails” as dependencies.