Table of contents
My side project turned into a playground for new technologies. Today I’ve set it up
rails-5.1rc1 and react.
I’ve been using yarn to manage frontend dependencies already. You’ll need to install yarn on your machine if you haven’t already. Also keep in mind, depending on how you’re deploying your app, your build server might need to have yarn installed, too. This article leaves out how to install yarn. Follow the setup instructions on the project’s website and it should be easy™.
While I was updating, I kept some notes in this post. They can possibly help or totally confuse you. Remember, this post is about Rails 5.1 RC1. Probably something will change in later released versions.
Installation of ruby dependencies
Gemfile, change the line with
gem ’rails’ ... to get bundler to
lock the version to the latest unstable 5.1 version. Also, you want to
install the new webpacker gem.
# Gemfile gem 'rails', '~> 5.1.0.rc1' gem 'webpacker'
bundle update. You’re on rails
The setup of the Webpack is still missing. Thankfully there are tasks to set everything up.
Installation of Webpack with webpacker
Now it’s time for:
When that’s done, you’ve setup the Webpack installation. Have a look at the newly created files (there are quite a few of them).
I found the additional webpacker tasks really handy. With their help, you can install your preferred JS framework without much hassle.
Installing React with webpacker
React is sticking on the top of my ’to learn’ list for quite a while.
To install it, do
rails webpacker:install:react and … voilà: react
(with JSX) set up.
OK, but how to use React now?
If you’ve already started
rails s… hold your horses: you need to start the
webpack development server. That’s new and you need to get used to it
(or change your project’s tmuxinator config).
The webpack server will build/transpile/apply the magic to
your JS code and serve these files. It runs on its own port, defaulting to 8080.
No need to worry about ports now, just start the webpack development server by
Start your rails server (
rails s) and open your app in your browser.
You shouldn’t be greeted with an Internal Server Error page anymore.
But still, there’s no visible React.
webpacker:install:react task installs the
hello_react example. Find it
To test it, add this to your HTML:
Save and refresh your browser. You should see a
at the end of your page now.
It’s really easy to setup Webpack in a Rails 5.1 project and use React. I haven’t tested it, but install helpers for Vue.js, Angular and some other popular frameworks exist. It should be just as easy.
Such an easy setup is possible due to great efforts by the webpacker gem. Kudos to everyone involved!