DEV Community

Christian Sedlmair
Christian Sedlmair

Posted on • Edited on

Setup Stimulus on Vite

Overview

Why?

Stimulus is essentially an initialiser. In this sense, it is an essential and necessary part of the setup, together with Hotwired.

However, when it comes to building reactive components, we believe it is the wrong tool for the job.

Setup

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

application.js

import { initStimulus } from "vite-stimulus-initializer"; const controllers = import.meta.glob('../javascript/**/*-controller.js', { eager: true }) initStimulus(controllers, 2, { debug: true, exclude: ['components', 'views'], folderSeparator: '-' }) 
Enter fullscreen mode Exit fullscreen mode

See naming options on vite-stimulus-initializer

Test Code

javascript/controllers/hello-controller.js

By the filename, the controller will be hooking on any element with data-controller="admin-hello".

import { Controller } from "@hotwired/stimulus" export default class extends Controller { connect() { // connect fires after the controller has found a corresponding element. console.log("Stimulus is connected", this.element) } static targets = [ "name" ] greet() { const element = this.nameTarget const name = element.value console.log(`Hello, ${name}!`) } } 
Enter fullscreen mode Exit fullscreen mode

any view in .haml

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

same in html.erb

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

by loading this you should see a «Stimulus is connected» in the console. Writing «John» in the input and clicking the button should print out a «Hello John!» on the console.

⚠️ Together with turbo you may see a double «Stimulus is connected» on the console (connect fires 2 times). Based on my Tests it is first firing on the old, element then turbo replaces this and then its firing on the new element, so it should't matter and the new element is not a double-initialized.

Continue with Stimulus Handbook

Good luck!

Overview

Top comments (0)