This is an example application of integrating React
and webpack
with Rails
.
bundle install
cd webpack && npm install
foreman start
./build.sh
- Edit
config/environments/development.rb
and set the asset_host if the source file matches the name, in this case we are usingmain.js
. Return the path to thewebpack hot dev server
assets path.
# config/environments/development.rb
config.action_controller.asset_host = Proc.new { |source|
if source =~ /main\.js$/i
"http://localhost:2992/assets"
end
}
- Edit
config/environments/production.rb
and add thewebpack/build/assets
path toconfig.assets.paths
.
# config/environments/production.rb
config.assets.paths << "#{Rails.root}/webpack/build/assets"
- Edit the
config/initializers/assets.rb
, and addmain.js
toassets.precompile
.
# config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( main.js )
- Define a
JAVASCRIPT_FRONTEND_PATH
constant, to set the asset path, in this case, when the env isproduction
, we set the constant toapp
, and Rails will look in the paths defined inassets
. In any other environment, we set the path to/main
, indevelopment
this will forceRails
to serve the asset from theasset_host
we defined.
# config/initializers/assets.rb
if Rails.env.production?
JAVASCRIPT_FRONTEND_PATH = 'app'
else
JAVASCRIPT_FRONTEND_PATH = '/main'
end
- In production
app
refers to theapp/assets/javascripts/app.js
. Where you can see it requires:
//= require main
Which refers to the webpack/build/assets/main.js
entry point that webpack will generate. We use this so we can get versioning on the entry point for free (well almost free, have to compile it again via asset pipeline).
- For the controller serving the
React
assets, we want to disable theapplication layout
.
# app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
layout false
def index
end
end
- We set the controller
index.html.erb
to as follows:
<!DOCTYPE html>
<html>
<head>
<title>RailsReactStarter</title>
</head>
<body>
<div id="content"></div>
<%= javascript_include_tag JAVASCRIPT_FRONTEND_PATH %>
</body>
</html>
- Now you should be good to go!