Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 21, 2022 08:55 pm GMT

Setup Stimulus on Vite

Overview

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!

Overview


Original Link: https://dev.to/chmich/setup-stimulus-on-vite-2eg9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To