Is it ok to call Application.start() more than once?

I’m trying to get chunks up and running and I have two seperate index.js files that load in all the controllers in their respective directories. They both import and call Application.start(). I’m wondering if it’s ok to call this twice?

Is there effectively two seperate applications running or does webpack magically provide the same object that start() is then called again on a second time?

It seems this would be the pattern:


import { Application } from "stimulus"

const application = Application.start()

export default application


import application from 'modules/stimulus'
import { definitionsFromContext } from "stimulus/webpack-helpers"

const context = require.context(".", true, /_controller\.js$/)

You can import application from modules/stimulus whenever you need to access that instance, and will only ever be running one ‘application’. This is my assumption anyway. Let me know if I’ve got it wrong.

Actually, I could be wrong about the above. Even when doing this:

import { Application } from "stimulus"

export const application = Application.start()

and importing that, I still end up with two seperate applications with their respective controller modules loaded in.

I suspect application.load is only intended to be run once per application? vs application.register

Hoping someone can shed some light :slight_smile:

The final answer here is that because I was using chunks, an application is started from each chunk file.

Chunks seem to be unable to share a reference to an object.

I guess these questions remain:

  • Is it possible to share a reference between chunks?
  • Is it ok to run more that one instance of Stimulus per page?

You could try assigning the Application instance to the global window object so access it from separate chunk.

// Chunk 1:
import { Application } from "stimulus"
window.application = new Application

// Chunk 2:
// can now access application object from window.
application.register("my-chunked-controller", MyChunkedController)

That would give you access to the application from any of your chunks, however the load order of the chunks would matter. To get around that, you could check to see if window.application is defined and set it if not, but I think you would need to import the Application for each chunk.

Thanks @brydave :slight_smile: That makes sense, though I’m hesitant to pollute the global namespace if I don’t have to.

From my searching, I think it might be possible to share a reference between chunks but it requires more complicated chunk config than the basic’s set by Webpacker. For now I’ve not seen any problems with running two seperate instances of Stimulus.