Sharing stimulus application between rails engine and rails application

Just getting started with stimulus and it’s a great experience so far – thanks for the wonderful framework!

I’m working in a Rails app which mounts a Rails Engine and I’m wondering what would be the ideal way to setup and use Stimulus in both. They are setup with webpack and I’m currently instantiating a Stimulus application in both using the neat webpack-helpers.

In the engine my setup looks like this:

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))

In the app I include the engine’s js and then instantiate yet another stimulus application:

import '@asgerb/engine'

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))

This sorta feels right conceptually, as the engine and the app could be considered two apps, but it feels wrong from a performance standpoint and I’m worried about possible side effects.

I’m hoping someone has an idea for how best to do this?

1 Like

@asgerb
I was trying to provide a stimulus controller to parent app.
here’s my question: https://www.reddit.com/r/rails/comments/somiwf/can_an_engine_add_a_stimulus_controller_rails_7/