DEV Community

Christian Sedlmair
Christian Sedlmair

Posted on • Edited on

3 1

Setup Stimulus on Vite

Overview

Stimulus is a «modest» Lightwight Library, created by the rails team that connects html and JavaScript. JS and html are in separated files.

Links

Stimulus-docs/Installation/hello-stimulus

Prerequisites

Vite

Setup

$ npm i @hotwired/stimulus stimulus-vite-helpers
Enter fullscreen mode Exit fullscreen mode

see: GitHub/stimulus-vite-helpers

frontend/controllers/index.js

import { Application } from '@hotwired/stimulus'
import { registerControllers } from 'stimulus-vite-helpers'

const application = Application.start()
const controllers = import.meta.globEager('./**/*_controller.js')
registerControllers(application, controllers)
Enter fullscreen mode Exit fullscreen mode

frontend/entrypoints/application.js

import '../controllers'
Enter fullscreen mode Exit fullscreen mode

Test Code

see: Stimulus Docs/is this thing on?

frontend/controllers/hello_controller.js

import { Controller } from "@hotwired/stimulus" 

export default class extends Controller {

    connect() { // => «connect» method is similar to initialize method in a ruby-class
        console.log("Hello, Stimulus!")
    }

    static targets = [ "name" ]

    greet() { // => doesnt matter for now, but later for the view
        const element = this.nameTarget
        const name = element.value
        console.log(`Hello, ${name}!`)
    }
}
Enter fullscreen mode Exit fullscreen mode

any view .haml

%div{"data-controller" => "hello"}
  %input{"data-hello-target" => "name", :type => "text"}/
  %button{"data-action" => "click->hello#greet"} Greet
Enter fullscreen mode Exit fullscreen mode

view in .html.erb

<div data-controller="hello">
  <input data-hello-target="name" type="text">/</input>
  <button data-action="click->hello#greet">Greet</button>
</div>
Enter fullscreen mode Exit fullscreen mode

=> Reload page and you should see «Hello Stimulus!» in Browser/developer Console.

=> type «User» in the input, click «Greet» button and you should see «Hello User!» in the Browser/Developer Console

Overview

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay