Without a Build System

I have a very simple one-page app where I’d like to use Stimulus. Currently, I’m not using any build system and I’d rather keeping it this way.

I understand I can use Stimulus without a build system and it works just fine.
However, since I have two controllers, I’d like to keep them in separate files (i.e. /assets/js/a_controller.js and /assets/js/b_controller.js).

I tried to simply move the controller code in a separate file and add a <script src="assets/js/a_controller.js"></script> tag just below importing Stimulus but I get Uncaught ReferenceError: Stimulus is not defined.

Is there a way to import/load the controllers for external files?


I have Stimulus working without a build system. IIRC, I had to include stimulus in the controller file. Not sure if that’s because I’m only using one controller (for now).

Name Generator by Ben Wilson, Author (https://benwilson.io/assets/controllers/haiku_controller.js)

use module imports:

import { Application } from "/path/to/stimulus.js";
import objectA from "/path/to/a_controller.js";
import objectB from "/path/to/b_controller.js";

window.Stimulus = Application.start();
Stimulus.register("a", objectA);
Stimulus.register("b", objectB);

Wrap this with a <script type="module"> tag.

Your controller.js files will look like this:

import { Controller } from "/path/to/stimulus.js";
export default class extends Controller {

using absolute paths will make things way easier.

If you can, use importmaps, it’s even easier. Both rails and Symfony have excellent support for impormaps and Stimulus, installed by default when creating a new project.