Work with Rails

What is the right way to organize JavaScript using stimulusjs in a Rails project?

1 Like

If you’re using Webpacker, I suggest putting your controllers in app/javascript/controllers/ and setting up your application in app/javascript/packs/application.js:

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start()
const context = require.context("controllers", true, /.js$/)
application.load(definitionsFromContext(context))

Webpacker will soon have an automatic installer that creates the same structure: https://github.com/rails/webpacker/pull/1244

2 Likes

Do you suggest to only use app/javascript/packs/application.js a pack and then having all the stimulus code in the app/javascript/controllrers?

What about stylesheets and images? Should they be in a pack and then imported from the javascript, or just in the assets/stylesheets and assets/images as usual?

You can also use it with plain old Javascript