Start Using Yarn With Rails Today

17 Feb 2017

Yarn is a JavaScript package manager,
and a faster alternative to NPM.
It works almost exactly like NPM, but has one advantage -
it creates a yarn.lock file which you can check into source control,
and make sure you’re running the same version of the packages everywhere.

Rails 5.1 will support Yarn out of the box,
but in the meanwhile, I wanted to try it out on a Rails 5.0 project.
I found the process surprisingly easy and painless.
Let’s see how you can add Bootstrap to an existing Rails project through Yarn.

First of all you need to install Yarn.
On macOS, you can use homebrew to install it using brew install yarn.
For other OSes, refer to the
installation instructions.

Next, run this command to create package.json.

yarn init

Next, let’s install bootstrap:

yarn add bootstrap

This will install bootstrap to node_modules/,
and also create yarn.lock with information about the package versions.
Remember to add node_modules/ to your .gitignore.

Next, we’ll ask Rails to look for assets in node_modules
by adding this line to config/initializers/assets.rb:

Tell application.css and application.js to load bootstrap’s assets,
by adding these lines:

# In app/assets/stylesheets/application.css:*=requirebootstrap/dist/css/bootstrap# In app/assets/javascripts/application.js://=requirebootstrap/dist/js/bootstrap

And that’s all there is to it.
You can restart your Rails server, and you’ll have bootstrap assets loaded.
This will not longer be necessary once Rails 5.1 ships,
but you can use this to start using Yarn with older Rails versions.

I have previously mentioned Rails Assets,
which is also a great option.
There were concerns about its future
at one point, but the team have done a great job maintaining it so far.
If you wish to avoid depending on Yarn now, it is a great option.
However, Yarn is set to become a part of Omakase Rails stack,
so it makes sense to start using it while we wait for the new Rails.

Links

Hi, I’m Nithin Bekal.
I work at Shopify in Ottawa, Canada.
Previously, co-founder of
CrowdStudio.in and
WowMakers.
Ruby is my preferred programming language,
and the topic of most of my articles here,
but I'm also a big fan of Elixir.
Tweet to me at @nithinbekal.