DEV Community

Christian Sedlmair
Christian Sedlmair

Posted on • Edited on

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

Top comments (0)