Skip to content

mikechau/rails-hot-react-webpack-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rails + React + Webpack

This is an example application of integrating React and webpack with Rails.

Getting Started

  1. bundle install
  2. cd webpack && npm install

Development

  1. foreman start

Production Build

  1. ./build.sh

Explanation

  1. Edit config/environments/development.rb and set the asset_host if the source file matches the name, in this case we are using main.js. Return the path to the webpack 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
  }
  1. Edit config/environments/production.rb and add the webpack/build/assets path to config.assets.paths.
# config/environments/production.rb
config.assets.paths << "#{Rails.root}/webpack/build/assets"
  1. Edit the config/initializers/assets.rb, and add main.js to assets.precompile.
# config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( main.js )
  1. Define a JAVASCRIPT_FRONTEND_PATH constant, to set the asset path, in this case, when the env is production, we set the constant to app, and Rails will look in the paths defined in assets. In any other environment, we set the path to /main, in development this will force Rails to serve the asset from the asset_host we defined.
# config/initializers/assets.rb
if Rails.env.production?
  JAVASCRIPT_FRONTEND_PATH = 'app'
else
  JAVASCRIPT_FRONTEND_PATH = '/main'
end
  1. In production app refers to the app/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).

  1. For the controller serving the React assets, we want to disable the application layout.
# app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
  layout false

  def index
  end
end
  1. 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>
  1. Now you should be good to go!

Links

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published