Adding Webpack and Stimulus.js

Modern Rails applications use JavaScript frameworks for interactivity.

Stimulus.js is a lightweight framework designed for Rails applications, making it a great fit for PWAs.

Step 1: Install Stimulus.js

Rails applications using Webpack (or esbuild) can install Stimulus with:

bin/rails stimulus:install

This creates a controllers directory in app/javascript.

Step 2: Example Stimulus Controller

Create a file at app/javascript/controllers/hello_controller.js:

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  connect() {
    console.log("Hello from Stimulus!");
  }
}

Then, link it in application.js:

import { Application } from "@hotwired/stimulus";
import HelloController from "./controllers/hello_controller";

const application = Application.start();
application.register("hello", HelloController);

Now, any HTML element can use Stimulus:

<div data-controller="hello">
  Open the console to see a Stimulus message!
</div>

This sets up JavaScript interactivity in our PWA. Next, we will configure HTTPS for service workers.