LoginSignup
48
52

More than 5 years have passed since last update.

Rails, React, Redux環境を用意してherokuで動くようにするまで手順メモ

Last updated at Posted at 2015-11-13

Railsなのはサクサク書けるから、Reduxなのは流行ってるっぽいからです。
サーバーサイドレンダリングもスパンと導入したいのでreact-railsgemを使った簡単バージョンです。Reduxも使うのでreact-railsだけだと困るからbrowserify-rails使おうかという流れです。

では早速、Railsのプロジェクトを用意します。

rails new rrrproject
cd rrrproject

Gemfileに以下を追記します。

gem 'browserify-rails'
gem 'react-rails'

おもむろにインストールします。

bundle install

config/application.rbにbrowserify用の設定を加えます。

config.browserify_rails.commandline_options = '-t babelify'

npmで関連パッケージを豪快にインストールします。
何故すべて--saveなのかはherokuで動かすためです。--save-devだとherokuデプロイ時にインストールしてもらえれませんでした。

npm install --save react redux react-dom react-redux redux-thunk browserify browserify-incremental babelify babel-preset-es2015 babel-preset-react

browserify-incrementalはbrowserify-railsで必要なものです。
また、今何も考えずに実行するともれなくbabel6系が入ると思います。babel6系はプラガブルに機能分割されているので今回使いたいbabel-preset-es2015babel-preset-reactを合わせて入れます。自分、ここで詰まりました。

で、色々インストールが完了したと思うので、reactのcomponentを作っていきましょう。

rails g react:install

ディレクトリとjsファイルが作られます。

app/assets/javascripts/components/以下に、componentを追加して、app/assets/javascripts/components.jsでglobalにぶら下げる感じです。

application.jsには以下を追加しておきます。reactはbrowserifyから呼びます。

//= require react_ujs
//= require components

あとプロジェクトルートに.babelrcを追加します。このプラグインを使ってくれよ、お願いだから、という指定です。

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

今回は環境構築なので、実際のredux, reactのコードは割愛します。
確認したい場合はreduxのexampleなどを持ってくると良いと思います。

上手くいってればここまでで、rails s出来ると思います。
以下のようなヘルパーを使えば、サーバーサイドレンダリングも確認できるでしょう。

<%= react_component('App') %>

それでは、次にherokuの準備です。

heroku create
heroku buildpacks:set heroku/ruby
heroku buildpacks:add --index 1 heroku/nodejs

nodeを使いたいからnodeとrubyのmulti buildpacksにしています。
以上です!エンジョイ!です。

サーバーサイドもGoやらelixirやらだとモダンさ3倍増しだと思うんですが、悩んで結局Railsの書きやすさ、ライブラリの多さにクラっときました。

ありがたや参考URL

http://astainforth.com/blogs/setting-up-react-in-ruby-on-rails-part-1
http://qiita.com/suzan2go/items/24ef3320e04b8a84597f
http://qiita.com/sawapi/items/e11d0cfbbacd078b2c3a

48
52
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
48
52