Hotwire Discussion

Using CoffeeScript 2 with Stimulus autoloader?

Hi there,

I’ve followed the Hotwire introduction video and now I’m wondering if I can somehow bring Stimulus to autoload controllers that are written in CoffeeScript, e.g.

assets
└── javascripts
    └── controllers
          └── reset_form_controller.coffee

So far I’ve added the coffee-rails gem, but that does not seem to do the trick. Any hints/ideas?

Since Rails 6, the javascript content is not handle pas sprocket (app/asset/javasript) but by webpacker (app/javascript). The Stimulus controllers are installed in /app/javasript/controllers/ by default.

The coffescript gem is useless in these circumstances. You need to install Coffeescript with Webpacker. You also need to edit /app/javascript/controllers/index.js to handle the context in such a way it accepts .coffe file as well.

And even then, I am not sure that will work.

/app/javascript/controllers/index.js

// Load all the controllers within this directory and all subdirectories.
// Controller files must be named *_controller.js.

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

const application = Application.start();
const context = require.context(
  "controllers",
  true,
  /_controller\.(coffee|js)$/
);

application.load(definitionsFromContext(context));

/app/javascript/bonjour_controller.coffee

import { Controller } from "stimulus"

export default class extends Controller 

  connect: ->
    console.log 'bonjour controller connected'
    this.element.textContent = 'Allo'

/app/views/home/index.haml

%h1 Home#index
%p Find me in app/views/home/index.html.haml

%div{data: {controller: 'bonjour'}}
  %input{type:'text'}
  %button Greet 

20210530_174640_Spectacle