There have been partial successful attempts like like react-rails gem, react-on-rails, webpack-rails, etc to help user bring JS in. Still, they all lacked somewhere. So here comes all new Rails 5.1 with webpack and yarn integrated.
I am doing a post on how to integrate Vue and Rails, so this is a follow up for how to get the app up and running.
Setting up the Webpacker gem
Add the following line to your
gem 'webpacker', github: 'rails/webpacker'
then run the following commands from your bash:
# to install the new gem bundle # to configure webpack bin/rails webpacker:install
This will generate an
ES6 syntax. These files will be compiled and available in your
So now we have written our first file and we want to use that, so we will want to have our webpack transpile these file for us. We can do so by running the command below in a separate terminal.
This will keep watching for all the changes we make to our file and bundle them.
You should also see a
package.json file created in your root which allows you to bring in any npm or bower packages. Let’s say we want to install lodash, we can simply do:
yarn add lodash
and now you have this npm asset available along with your rails assets pipeline, pretty cool huh?
This is very powerful if you don’t know. Previously rails developer need to be dependent on some wrapper gem, which will most probably not updated very frequently. So this saves us all those headache.
The webpacker gem tries to help you start your project with ease and thus come with preconfigured with react, vue and angular. You can start using anyone of them with the respective command below:
rails webpacker:install:react rails webpacker:install:angular rails webpacker:install:vue
There are still few things like getting all of these to work while keeping
turbolinks and how to structure the code. All these things are yet to get more concrete. In the meanwhile, whatever we have now is pretty powerful and helps achive a lot. I hope you find this post helpful. Thanks for reading.