Installing Stimulus
Learn to install Stimulus locally in this lesson.
Stimulus is one of the frameworks Webpacker is aware of, and, because of that, there’s a default path to installation within our Rails app.
The first thing we are going to do to install Stimulus is remove application/javascript/src
and reset application/javascript/packs/application.ts
back to its original application/javascript/packs/application.js
form (the Stimulus installer expects it there). Then, we’re going to use Webpacker’s installer to add Stimulus:
$ bundle exec rails webpacker:install:stimulus
Here’s what the Stimulus installer does for us:
- The installer adds
stimulus
as a package to thepackage.json
file. - It appends the line
import controllers
to theapplication.js
file. - It adds the directory,
app/javascript/controllers
. - In that directory is the file,
app/javascript/controllers/index.js
, which includes information on auto loading the Stimulus code we’re going to write. We’re going to leave it alone for the moment. - It also adds a sample file, called
app/javascript/controllers/hello_controller.js
.
This chapter uses Stimulus 2.0, which has not yet been released as of this writing. So, in order to use the pre-release version of Stimulus, you need to change the stimulus
entry in the package.json
file to this (the long URL needs to be all on one line):
"stimulus": "https://github.com/stimulusjs/dev-builds/archive/b8cc8c4/stimulus.tar.gz"
There’s a discussion on GitHub that you can look at for more details.
Please note that there must be an app/javascript/packs/application.js
file or the installation will fail. This is a bug in the installer. Maybe it will be fixed by the time you read this. In the meantime, we temporarily renamed application.ts
then named it back.
In order to prep for using TypeScript with Stimulus and to write our own code, you need to do two things:
- Delete the sample file at
app/javascript/controllers/hello_controller.js
. We don’t need it. - In the
app/javascript/controllers/index.js
file, you’ll see the following on line 8:
const context = require.context("controllers", true, /_controller\.js$/)
Change it to:
const context = require.context("controllers", true, /_controller\.ts$/)
This allows Stimulus to see our TypeScript controllers.
Leaving things alone
We’re leaving theindex.js
file itself in JavaScript rather than converting it to TypeScript for the moment. We will come back to it in an upcoming installation lesson.
Get hands-on with 1400+ tech skills courses.