Start Using Yarn With Rails Today
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
Next, run this command to create
Next, let’s install
This will install bootstrap to
and also create
yarn.lock with information about the package versions.
Remember to add
node_modules/ to your
Next, we’ll ask Rails to look for assets in
by adding this line to
application.js to load bootstrap’s assets,
by adding these lines:
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 cencerns 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.