LoginSignup
27
28

More than 5 years have passed since last update.

RailsにReactとES6とMaterial-UIを導入する手順(sprockets-commoner gemを使って)

Last updated at Posted at 2017-02-12

背景

普段Railsでreactを書く時はreact-rails gemを導入した環境で書いている。構築が簡単なのでreactを素で書くためであれば、これで十分と思っていた。

しかし、パッケージのキャッチアップが遅れがちになるのが欠点。さらに、rails単体でnpmで多数配布されている先進的なパッケージの恩恵にあずかれない。(表題にあるMaterial-UIを使いたい!)

react-railsに頼らない方法だとwebpackを導入して行う事例が多数報告されている。しかし、sprocketsを無効化したりすごい面倒そう。

と、思っていたら、sporocketsを活かしてトランスパイルできるgem「sprockets-commoner
」の記事を発見。gem自体は2016年に発表されたらしいので比較的新しい。

sprockets-commonerはsprocketsのコンパイル時にbabelでついでにトランスパイルしてくれるそう。webpackを使った手法よりも、sprocketsをそのまま活かせるのでシステム移行のコスト(作業量)を抑えることが期待できる。

目的

  • Railsでreactが使える環境を整える。(hello npm package! good-bye react-rails gem !)
  • react-railsでは手を出しづらかったMaterial UIパッケージを導入して、動作確認をする

環境

  • macOS Sierra
  • ruby 2.3.1
  • node 7.5.0
  • yarn 0.19.1
    • npmと同様にパッケージを導入できる
    • npmを使ってもOK

(nodeとyarnはhomebrewでインストールしました。)

完成品

下記からcloneし、以下のコマンドを打ち、localhost:3000/items にアクセスすればたぶんOK。

$ cd muiapp
$ yarn install
$ bundle install
$ rake db:migrate
$ rails s

概要

  1. Railsインストール
  2. yarnでパッケージインストール
  3. Gem(sprockets-commoner)インストール
  4. トランスパイラ用設定(.babelrc)
  5. トランスパイラ用設定(Railsの色々)
  6. Material UI動作確認

手順

トラブルシューティングに役立つかもと思って、インストール時のコンソールの出力をほぼ全てのせました。

Railsインストール

普通にやるだけ。

まずbundle initして初期Gemfileを作成する。

mkdir muiapp
cd muiapp
bundle init

railsのコメントアウトを外す。

# frozen_string_literal: true
source "https://rubygems.org"

gem "rails"

bundle installする。主題と関係ないけど--pathの指定忘れずに。

$ bundle install --path vendor/bundler

Fetching gem metadata from https://rubygems.org/..........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Installing rake 12.0.0
Installing concurrent-ruby 1.0.4
Installing i18n 0.8.0
Installing minitest 5.10.1
Installing thread_safe 0.3.5
Installing builder 3.2.3
Installing erubis 2.7.0
Installing mini_portile2 2.1.0
Installing rack 2.0.1
Installing nio4r 1.2.1 with native extensions
Installing websocket-extensions 0.1.2
Installing mime-types-data 3.2016.0521
Installing arel 7.1.4
Using bundler 1.14.3
Installing method_source 0.8.2
Installing thor 0.19.4
Installing tzinfo 1.2.2
Installing nokogiri 1.7.0.1 with native extensions
Installing rack-test 0.6.3
Installing sprockets 3.7.1
Installing websocket-driver 0.6.5 with native extensions
Installing mime-types 3.1
Installing activesupport 5.0.1
Installing loofah 2.0.3
Installing mail 2.6.4
Installing rails-dom-testing 2.0.2
Installing globalid 0.3.7
Installing activemodel 5.0.1
Installing rails-html-sanitizer 1.0.3
Installing activejob 5.0.1
Installing activerecord 5.0.1
Installing actionview 5.0.1
Installing actionpack 5.0.1
Installing actioncable 5.0.1
Installing actionmailer 5.0.1
Installing railties 5.0.1
Installing sprockets-rails 3.2.0
Installing rails 5.0.1
Bundle complete! 1 Gemfile dependency, 38 gems now installed.
Bundled gems are installed into ./vendor/bundler.

Rails newする。

今回はやらなかったが、後半、turbolinksの記述を削除するので、tubolinksを外すオプションをつけてrails newすると後でちょっと楽出来るかも。

bundle exec rails new .

       exist  
      create  README.md
      create  Rakefile
      create  config.ru
      create  .gitignore
    conflict  Gemfile
Overwrite /muiapp/Gemfile? (enter "h" for help) [Ynaqdh] Y
       force  Gemfile
      create  app
      create  app/assets/config/manifest.js
      create  app/assets/javascripts/application.js
      create  app/assets/javascripts/cable.js
      create  app/assets/stylesheets/application.css
      create  app/channels/application_cable/channel.rb
      create  app/channels/application_cable/connection.rb
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/jobs/application_job.rb
      create  app/mailers/application_mailer.rb
      create  app/models/application_record.rb
      create  app/views/layouts/application.html.erb
      create  app/views/layouts/mailer.html.erb
      create  app/views/layouts/mailer.text.erb
      create  app/assets/images/.keep
      create  app/assets/javascripts/channels
      create  app/assets/javascripts/channels/.keep
      create  app/controllers/concerns/.keep
      create  app/models/concerns/.keep
      create  bin
      create  bin/bundle
      create  bin/rails
      create  bin/rake
      create  bin/setup
      create  bin/update
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/secrets.yml
      create  config/cable.yml
      create  config/puma.rb
      create  config/spring.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/application_controller_renderer.rb
      create  config/initializers/assets.rb
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/cookies_serializer.rb
      create  config/initializers/cors.rb
      create  config/initializers/filter_parameter_logging.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/new_framework_defaults.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  lib
      create  lib/tasks
      create  lib/tasks/.keep
      create  lib/assets
      create  lib/assets/.keep
      create  log
      create  log/.keep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/apple-touch-icon-precomposed.png
      create  public/apple-touch-icon.png
      create  public/favicon.ico
      create  public/robots.txt
      create  test/fixtures
      create  test/fixtures/.keep
      create  test/fixtures/files
      create  test/fixtures/files/.keep
      create  test/controllers
      create  test/controllers/.keep
      create  test/mailers
      create  test/mailers/.keep
      create  test/models
      create  test/models/.keep
      create  test/helpers
      create  test/helpers/.keep
      create  test/integration
      create  test/integration/.keep
      create  test/test_helper.rb
      create  tmp
      create  tmp/.keep
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.keep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.keep
      remove  config/initializers/cors.rb
         run  bundle install
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform mingw, mswin, x64_mingw, jruby`.
Fetching gem metadata from https://rubygems.org/..........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Using rake 12.0.0
Using concurrent-ruby 1.0.4
Using i18n 0.8.0
Using minitest 5.10.1
Using thread_safe 0.3.5
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using rack 2.0.1
Using nio4r 1.2.1
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 7.1.4
Using bundler 1.14.3
Installing byebug 9.0.6 with native extensions
Installing coffee-script-source 1.12.2
Installing execjs 2.7.0
Using method_source 0.8.2
Using thor 0.19.4
Installing debug_inspector 0.0.2 with native extensions
Installing ffi 1.9.17 with native extensions
Installing multi_json 1.12.1
Installing rb-fsevent 0.9.8
Installing puma 3.7.0 with native extensions
Installing sass 3.4.23
Installing tilt 2.0.6
Installing sqlite3 1.3.13 with native extensions
Installing turbolinks-source 5.0.0
Using tzinfo 1.2.2
Using nokogiri 1.7.0.1
Using rack-test 0.6.3
Using sprockets 3.7.1
Using websocket-driver 0.6.5
Using mime-types 3.1
Installing coffee-script 2.4.1
Installing uglifier 3.0.4
Installing rb-inotify 0.9.8
Installing turbolinks 5.0.1
Using activesupport 5.0.1
Using loofah 2.0.3
Using mail 2.6.4
Installing listen 3.0.8
Using rails-dom-testing 2.0.2
Using globalid 0.3.7
Using activemodel 5.0.1
Installing jbuilder 2.6.1
Installing spring 2.0.1
Using rails-html-sanitizer 1.0.3
Using activejob 5.0.1
Using activerecord 5.0.1
Installing spring-watcher-listen 2.0.1
Using actionview 5.0.1
Using actionpack 5.0.1
Using actioncable 5.0.1
Using actionmailer 5.0.1
Using railties 5.0.1
Using sprockets-rails 3.2.0
Installing coffee-rails 4.2.1
Installing jquery-rails 4.2.2
Installing web-console 3.4.0
Using rails 5.0.1
Installing sass-rails 5.0.6
Bundle complete! 15 Gemfile dependencies, 62 gems now installed.
Bundled gems are installed into ./vendor/bundler.
         run  bundle exec spring binstub --all
* bin/rake: spring inserted
* bin/rails: spring inserted


yarnでパッケージインストール

yarnはnpmと同じようなjavascriptのパッケージマネージャ。

今回はyarnを使ったけどnpmでもOK。

まずyarn initをしてpackage.jsを作成する。

$ yarn init
yarn init v0.19.1
question name (muiapp): 
question version (1.0.0): 
question description: 
question entry point (index.js): 
question repository url ([object Object]): 
question author: 
question license (MIT): 
success Saved package.json
✨  Done in 5.63s.

yarn addで以下のパッケージをインストールする

  • react用
    • react
    • react-dom
    • react-tab-event-plugin
  • babel用
    • babel-core
    • babel-preset-react --devオプション
    • babel-preset-es2015 --devオプション
  • material-ui用
    • material-ui
$ yarn add react react-dom react-tap-event-plugin
yarn add v0.19.1
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning "react-dom@15.4.2" has unmet peer dependency "react@^15.4.2".
warning "react-tap-event-plugin@2.0.1" has unmet peer dependency "react@^15.4.0-0".
warning "react-tap-event-plugin@2.0.1" has unmet peer dependency "react-dom@^15.4.0-0".
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 18 new dependencies.
├─ asap@2.0.5
├─ core-js@1.2.7
├─ encoding@0.1.12
├─ fbjs@0.8.9
├─ iconv-lite@0.4.15
├─ is-stream@1.1.0
├─ isomorphic-fetch@2.2.1
├─ js-tokens@3.0.1
├─ loose-envify@1.3.1
├─ node-fetch@1.6.3
├─ object-assign@4.1.1
├─ promise@7.1.1
├─ react-dom@15.4.2
├─ react-tap-event-plugin@2.0.1
├─ react@15.4.2
├─ setimmediate@1.0.5
├─ ua-parser-js@0.7.12
└─ whatwg-fetch@2.0.2
✨  Done in 2.44s.

$ yarn add babel-core
yarn add v0.19.1
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 47 new dependencies.
├─ ansi-regex@2.1.1
├─ ansi-styles@2.2.1
├─ babel-code-frame@6.22.0
├─ babel-core@6.22.1
├─ babel-generator@6.22.0
├─ babel-helpers@6.22.0
├─ babel-messages@6.22.0
├─ babel-register@6.22.0
├─ babel-runtime@6.22.0
├─ babel-template@6.22.0
├─ babel-traverse@6.22.1
├─ babel-types@6.22.0
├─ babylon@6.15.0
├─ balanced-match@0.4.2
├─ brace-expansion@1.1.6
├─ chalk@1.1.3
├─ concat-map@0.0.1
├─ convert-source-map@1.3.0
├─ debug@2.6.1
├─ detect-indent@4.0.0
├─ escape-string-regexp@1.0.5
├─ esutils@2.0.2
├─ globals@9.14.0
├─ has-ansi@2.0.0
├─ home-or-tmp@2.0.0
├─ invariant@2.2.2
├─ is-finite@1.0.2
├─ jsesc@1.3.0
├─ json5@0.5.1
├─ lodash@4.17.4
├─ minimatch@3.0.3
├─ minimist@0.0.8
├─ mkdirp@0.5.1
├─ ms@0.7.2
├─ number-is-nan@1.0.1
├─ os-homedir@1.0.2
├─ os-tmpdir@1.0.2
├─ path-is-absolute@1.0.1
├─ private@0.1.7
├─ regenerator-runtime@0.10.1
├─ repeating@2.0.1
├─ slash@1.0.0
├─ source-map-support@0.4.11
├─ source-map@0.5.6
├─ strip-ansi@3.0.1
├─ supports-color@2.0.0
└─ to-fast-properties@1.0.2
✨  Done in 3.23s.

$ yarn add babel-preset-react --dev
yarn add v0.19.1
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 10 new dependencies.
├─ babel-helper-builder-react-jsx@6.22.0
├─ babel-plugin-syntax-flow@6.18.0
├─ babel-plugin-syntax-jsx@6.18.0
├─ babel-plugin-transform-flow-strip-types@6.22.0
├─ babel-plugin-transform-react-display-name@6.22.0
├─ babel-plugin-transform-react-jsx-self@6.22.0
├─ babel-plugin-transform-react-jsx-source@6.22.0
├─ babel-plugin-transform-react-jsx@6.22.0
├─ babel-preset-react@6.22.0
└─ esutils@2.0.2
✨  Done in 2.10s.

$ yarn add babel-preset-es2015 --dev
yarn add v0.19.1
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 41 new dependencies.
├─ babel-helper-call-delegate@6.22.0
├─ babel-helper-define-map@6.22.0
├─ babel-helper-function-name@6.22.0
├─ babel-helper-get-function-arity@6.22.0
├─ babel-helper-hoist-variables@6.22.0
├─ babel-helper-optimise-call-expression@6.22.0
├─ babel-helper-regex@6.22.0
├─ babel-helper-replace-supers@6.22.0
├─ babel-plugin-check-es2015-constants@6.22.0
├─ babel-plugin-transform-es2015-arrow-functions@6.22.0
├─ babel-plugin-transform-es2015-block-scoped-functions@6.22.0
├─ babel-plugin-transform-es2015-block-scoping@6.22.0
├─ babel-plugin-transform-es2015-classes@6.22.0
├─ babel-plugin-transform-es2015-computed-properties@6.22.0
├─ babel-plugin-transform-es2015-destructuring@6.22.0
├─ babel-plugin-transform-es2015-duplicate-keys@6.22.0
├─ babel-plugin-transform-es2015-for-of@6.22.0
├─ babel-plugin-transform-es2015-function-name@6.22.0
├─ babel-plugin-transform-es2015-literals@6.22.0
├─ babel-plugin-transform-es2015-modules-amd@6.22.0
├─ babel-plugin-transform-es2015-modules-commonjs@6.22.0
├─ babel-plugin-transform-es2015-modules-systemjs@6.22.0
├─ babel-plugin-transform-es2015-modules-umd@6.22.0
├─ babel-plugin-transform-es2015-object-super@6.22.0
├─ babel-plugin-transform-es2015-parameters@6.22.0
├─ babel-plugin-transform-es2015-shorthand-properties@6.22.0
├─ babel-plugin-transform-es2015-spread@6.22.0
├─ babel-plugin-transform-es2015-sticky-regex@6.22.0
├─ babel-plugin-transform-es2015-template-literals@6.22.0
├─ babel-plugin-transform-es2015-typeof-symbol@6.22.0
├─ babel-plugin-transform-es2015-unicode-regex@6.22.0
├─ babel-plugin-transform-regenerator@6.22.0
├─ babel-plugin-transform-strict-mode@6.22.0
├─ babel-preset-es2015@6.22.0
├─ babel-runtime@6.22.0
├─ babel-types@6.22.0
├─ regenerate@1.3.2
├─ regenerator-transform@0.9.8
├─ regexpu-core@2.0.0
├─ regjsgen@0.2.0
└─ regjsparser@0.1.5
✨  Done in 2.02s.

$ yarn add material-ui 
yarn add v0.19.1
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 18 new dependencies.
├─ babel-runtime@6.22.0
├─ bowser@1.6.0
├─ change-emitter@0.1.2
├─ hoist-non-react-statics@1.2.0
├─ hyphenate-style-name@1.0.2
├─ inline-style-prefixer@2.0.5
├─ keycode@2.1.8
├─ lodash.merge@4.6.0
├─ lodash.throttle@4.1.1
├─ material-ui@0.16.7
├─ react-addons-create-fragment@15.4.2
├─ react-addons-shallow-compare@15.4.2
├─ react-addons-transition-group@15.4.2
├─ react-event-listener@0.4.1
├─ recompose@0.21.2
├─ simple-assign@0.1.0
├─ symbol-observable@1.0.4
└─ warning@3.0.0
✨  Done in 3.25s.

$ yarn add create-react-class
yarn add v1.7.0
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning " > react-tap-event-plugin@3.0.3" has incorrect peer dependency "react@^16.0.0-0 < 16.4.0".
warning " > react-tap-event-plugin@3.0.3" has incorrect peer dependency "react-dom@^16.0.0-0 < 16.4.0".
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ create-react-class@15.6.3
info All dependencies
└─ create-react-class@15.6.3
✨  Done in 2.08s.

トランスパイラ用設定(.babelrc)

アプリ直下に.babelrcを作成して、下記の内容を貼り付ける。
babelでes6とreactをトランスパイルさせるための指定。

{
  "presets": [
      "es2015",
      "react"
  ]
}

トランスパイラ用設定(Railsの色々)

sprockets-commonerインストール

Gemfileに下記を追加

##### 省略 #####
# for es6 react etc.
gem 'sprockets-commoner'

もちろんbundle installする。

$ bundle install                
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform mingw, mswin, x64_mingw, jruby`.
Fetching gem metadata from https://rubygems.org/..........
Fetching version metadata from https://rubygems.org/..
Fetching dependency metadata from https://rubygems.org/.
Resolving dependencies...
Using rake 12.0.0
Using concurrent-ruby 1.0.4
Using i18n 0.8.0
Using minitest 5.10.1
Using thread_safe 0.3.5
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using rack 2.0.1
Using nio4r 1.2.1
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 7.1.4
Using bundler 1.14.3
Using byebug 9.0.6
Using coffee-script-source 1.12.2
Using execjs 2.7.0
Using method_source 0.8.2
Using thor 0.19.4
Using debug_inspector 0.0.2
Using ffi 1.9.17
Using multi_json 1.12.1
Using rb-fsevent 0.9.8
Using puma 3.7.0
Using sass 3.4.23
Using tilt 2.0.6
Installing schmooze 0.1.6
Using sqlite3 1.3.13
Using turbolinks-source 5.0.0
Using tzinfo 1.2.2
Using nokogiri 1.7.0.1
Using rack-test 0.6.3
Using sprockets 3.7.1
Using websocket-driver 0.6.5
Using mime-types 3.1
Using coffee-script 2.4.1
Using uglifier 3.0.4
Using rb-inotify 0.9.8
Using turbolinks 5.0.1
Using activesupport 5.0.1
Using loofah 2.0.3
Installing sprockets-commoner 0.6.3
Using mail 2.6.4
Using listen 3.0.8
Using rails-dom-testing 2.0.2
Using globalid 0.3.7
Using activemodel 5.0.1
Using jbuilder 2.6.1
Using spring 2.0.1
Using rails-html-sanitizer 1.0.3
Using activejob 5.0.1
Using activerecord 5.0.1
Using spring-watcher-listen 2.0.1
Using actionview 5.0.1
Using actionpack 5.0.1
Using actioncable 5.0.1
Using actionmailer 5.0.1
Using railties 5.0.1
Using sprockets-rails 3.2.0
Using coffee-rails 4.2.1
Using jquery-rails 4.2.2
Using web-console 3.4.0
Using rails 5.0.1
Using sass-rails 5.0.6
Bundle complete! 16 Gemfile dependencies, 64 gems now installed.
Bundled gems are installed into ./vendor/bundler.

Railsのファイルを設定する

ここが一番重要。目的は以下の2点

  • turbolinksを無効にする
  • jsx.jsファイルを読みこむようにassetsに追加する

tubolinksを無効にする

application.html.erb内の stylesheet_link_tagjavascript_include_tagturbolinks の記述を取り除く。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Muiapp</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all' %>
    <%= javascript_include_tag 'application', media: 'all' %>
  </head>

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

重要 application.js内のturbolinksで使われる記述( //= require turbolinks//= require_tree . )を下記の様に削除する。

app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs

jsx.jsファイルを読みこめるようにassetsに追加する

重要 jsx.jsファイルを扱えるよう、 Rails.application.config.assets.precompile += %w( *.jsx.js ) の記述をassets.rbに追加

config/initializers/assets.rb
# Be sure to restart your server when you modify this file.

# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'

# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += %w( *.jsx.js )

That's all.
これで、Material UIを使う準備できた!

Material Ui動作確認

ようやくmaterial UIの動作を確認する!

Itemモデルを新規作成する。(reactと Material-UIの動作確認で、Railsとデータのやりとりしないので特にカラム追加不要。)

$ bundle exec rails g model item
Running via Spring preloader in process 94718
muiapp/vendor/bundler/ruby/2.3.0/gems/spring-2.0.1/lib/spring/application.rb:175: warning: Insecure world writable dir /usr/local in PATH, mode 040777
Expected string default value for '--jbuilder'; got true (boolean)
      invoke  active_record
      create    db/migrate/20170212115245_create_items.rb
      create    app/models/item.rb
      invoke    test_unit
      create      test/models/item_test.rb
      create      test/fixtures/items.yml

$ bundle exec rake db:migrate   
== 20170212115245 CreateItems: migrating ======================================
-- create_table(:items)
   -> 0.0012s
== 20170212115245 CreateItems: migrated (0.0013s) =============================

Itemsのアクセスの振り分けを書く。

config/routes.rb
Rails.application.routes.draw do
  match 'items', to: 'items#index', via: [:get], as: 'items'
end

コントローラにindexメソッドを配置。ただviewを表示すればいいので、空のまま。

app/controllers/items_controller.rb
class ItemsController < ApplicationController
  def index
  end
end

views内でjavascriptを呼び込む。そのためjavascript_include_tagを追加。

ractの目印(描画される箇所)としてid="root"を設定

app/views/items/index.html.erb
<%= javascript_include_tag 'item.jsx' %>

<div id="root">
</div>

Material UIを使った事例

app/assets/javascripts/item.jsx.js
import React from "react";
import ReactDOM from "react-dom";
import injectTapEventPlugin from 'react-tap-event-plugin';
import {getMuiTheme, MuiThemeProvider} from 'material-ui/styles';
import {RaisedButton, TextField, AppBar, Chip} from 'material-ui';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';

injectTapEventPlugin();

var createReactClass = require('create-react-class');
var Index = React.createClass({
  getInitialState: function() {
    return {message: ''};
  },
  send: function(e) {
    e.preventDefault();
    this.setState({message: '', sentMessage: this.state.message.trim()});
  },
  handleChange: function(e) {
    this.setState({message: e.target.value});
  },

  render: function() {
    return (
      <div>
        <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
          <div>
            <AppBar title="Title" iconClassNameRight="muidocs-icon-navigation-expand-more"/>
            <h1>Material UI テスト</h1>
            <form onSubmit={this.send}>
              <TextField hintText="テキスト入力" floatingLabelText="ここに入力して送信" value={this.state.message} onChange={this.handleChange}/>
              <RaisedButton label="送信" primary={true} onClick={this.send}></RaisedButton>
              <Chip>
                {this.state.sentMessage}
              </Chip>
            </form>
          </div>
        </MuiThemeProvider>
      </div>
    );
  }
});

window.onload = function() {
  ReactDOM.render(
    <Index/>, document.getElementById("root"));
};


/itemsにアクセスして下記のような画面が表示されたら成功!
https://gyazo.com/534732a75ffabbc9573e9d22feaccc0e

メモ

  • 重要なのはturbolinksを外すこと。これが必要なことがわからなくて半日悩んだ。
  • jsxファイルの拡張子はjs.jsxではなく、jsx.jsを使うこと。すなわち末尾が.jsで終わるファイル名にする。 例えば、 <%= javascript_include_tag 'item.jsx' %> が参照するファイルはitem.jsx.js。勝手に末尾にjsをつけてくるので、末尾を必ずjsで終えないとだめ。
  • * bootstrapを使いたい場合はyarn add react-bootstrap
27
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
28