bokunonikki.net
JP / EN

Railsでstimulus.jsを使う

Thu Feb 21, 2019
Thu Feb 21, 2019

環境

  • macOS Mojave 10.14.3
  • Rails 5.2.2
  • ruby 2.6.1

Stimulusとは

RailsでおなじみのBasecampメンバーによって開発されたJavascriptフレームワークです。当然、railsと相性がよく、turbolinksとも共存可能です。

専任のフロントエンジニアがいない場合や個人開発などの少人数開発にぴったりのJavascriptフレームワークです。

公式ドキュメント

はじめる

gemはプロジェクトごとに管理したいので以下のようにする。

1
2
3
$ mkdir stimulus
$ cd stimulus
$ bundle init

Gemfileを編集

1
2
3
4
5
6
7
8
9
# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

# gem "rails"

gem 'rails', '~> 5.2.2'

次にbundle install --path vendor/bundleを実行。次回からは--path vendor/bundleは不要。

1
$ bundle install --path vendor/bundle

Rails new

rails new --webpack=stimulusでもstimulusをインストールできるらしいのですが、僕の場合はwebpack側の設定でエラー出て修正するのが面倒だったので後からstimulusをインストールすることにしました。

1
2
3
$ bundle exec rails new . -B -d postgresql  --skip-coffee
$ bundle exec rails db:create
$ bundle exec rails s

bundle exec rails db:create後、以下のようなエラーが出た場合。

Could not find gem 'pg (>= 0.18, < 2.0)' in any of the gem sources listed in your Gemfile.

1
2
3
$ brew uninstall postgresql
$ brew install postgresql
$ bundle install --path vendor/bundle

Webpacker gemのインストール

Webpacker gemをインストールします。 Gemfileに以下の行を追加し、bundle install。gem 'webpacker', github: 'rails/webpacker'だとバージョン4がインストールされエラーになったのでここではバージョンを指定してインストールします。

1
2
# Gemfile
gem 'webpacker', '~> 3.5'

bin/rails webpacker:installを実行。Yarnをインストールしてない場合はYarnを事前にインストールしておいてください。

1
$ bin/rails webpacker:install

Stimulusをインストール

1
$ bundle exec rails webpacker:install:stimulus

ここまで終わるとapp/javascripts/packs/application.jsが以下のようになっていると思います。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# app/javascripts/packs/application.js
/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
console.log('Hello World from Webpacker')

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start()
const context = require.context("./controllers", true, /\.js$/)
application.load(definitionsFromContext(context))

次にviews/layouts/application.html.erbに<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>を追記します。

参考 webpacker

参考 stimulus Handbook

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Stimulus</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

これでstimulusの設定は終わり。

hello stimulusを作る

1
$ rails g controller Hello index

view

1
2
3
4
5
6
7
8
# views/hello/index.html.erb

<h1>Hello#index</h1>
<p>Find me in app/views/hello/index.html.erb</p>

<div data-controller="hello">
  <h1 data-target="hello.output"></h1>
</div>

次にhello_controller.jsを作ります。以下のディレクトリ直下におきます。

app/javascripts/packs/controllers/hello_controller.js

1
2
3
4
5
6
7
8
9
// app/javascripts/packs/controllers/hello_controller.js

import { Controller } from "stimulus"
export default class extends Controller {
  static targets = [ "output" ]
  connect() {
    this.outputTarget.textContent = 'Hello, Stimulus!'
  }
}

Railsでstimulus.jsを使う

強いチームはオフィスを捨てる: 37シグナルズが考える「働き方革命」

See Also