An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
Setup Stimulus on Vite
Stimulus and Svelte having totally different strengths:
Svelte holds JS and html in one file and is a mighty tool for making complex things super easy. It is able for running conditions or loops in the html template, like known in rails views.
Stimulus, built from the rails people, is a modest library for connecting js to the rails-views.
Thats the difference!
Without Stimulus there would be failing one part of the symphony. Its the part that we previously built with cumbersome initializers or jQuery.
Setup
$ npm i @hotwired/stimulus stimulus-vite-helpers
application.js
import { Application } from '@hotwired/stimulus'import { registerControllers } from 'stimulus-vite-helpers'const application = Application.start()import '../javascript/controllers/hello_controller'const controllers = import.meta.globEager('../controllers/**/*_controller.js')registerControllers(application, controllers)
Test Code
javascript/controllers/hello_controller.js
Thanks to conventions, on the filename, the controller will be hooking on any element with data-controller="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) } greet() { console.log("button clicked!", this) }}
any view in .haml
%div{ 'data-controller' => 'hello' } %input{:type => "text"}/ %button{ 'data-action' => "click->hello#greet" } Greet
same in html.erb
<div data-controller="hello"> <input type="text">/</input> <button data-action="click->hello#greet">Greet</button></div>
by loading this you should see a Stimulus is connected in the console and clicking the button should print out a button clicked on the console.
Continue with Stimulus Handbook
Good luck!
Original Link: https://dev.to/chmich/setup-stimulus-on-vite-2eg9
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To