published: 19th of January 2021
In this post I will cover the process of installing and getting started with StimulusJS in a Rails 6 app.
The following software was used in this post.
Install Stimulus with the bundle exec rails webpacker:install:stimulus command.
bundle exec rails webpacker:install:stimulus # output Installing all Stimulus dependencies run yarn add stimulus from "." yarn add v1.22.5 [1/4] Resolving packages... [2/4] Fetching packages... info firstname.lastname@example.org: The platform "linux" is incompatible with this module. info "email@example.com" is an optional dependency and failed compatibility check. Excluding it from installation. info firstname.lastname@example.org: The platform "linux" is incompatible with this module. info "email@example.com" is an optional dependency and failed compatibility check. Excluding it from installation. [3/4] Linking dependencies... warning " > firstname.lastname@example.org" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0". warning "webpack-dev-server > email@example.com" has unmet peer dependency "webpack@^4.0.0". [4/4] Building fresh packages... success Saved lockfile. success Saved 5 new dependencies. info Direct dependencies └─ firstname.lastname@example.org info All dependencies ├─ @email@example.com ├─ @firstname.lastname@example.org ├─ @email@example.com ├─ @firstname.lastname@example.org └─ email@example.com Done in 4.08s. Webpacker now supports Stimulus.js 🎉
This will install Stimulus and also in typical rails fashion the following boilerplate files/folders will be created.
I will use the example code from the Stimuls website for the next section.
At the time of writing the code for the hello_controller.js file generated by the install process was not compatible with the example code from the website.
Change the file to the following contents.
In some view add the following example content.
# app/views/examples/index.html.erb <!--HTML from anywhere--> <div data-controller="hello"> <input data-hello-target="name" type="text"> <button data-action="click->hello#greet"> Greet </button> <span data-hello-target="output"> </span> </div>
This will create an input like the below.
Type something in the box and press the Greet button.
If everything is setup correctly you will see some output next to the input box.
If not, open the inspector console in your browser and check for any errors.
In this post I covered the process of installing and using Stimulus JS in a Rails 6 application. Do you feel stimulated? I know I do!