(1) Install yarn.

(a) For Mac:

brew install yarn

(b) For Ubuntu:

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update
sudo apt-get install yarn

(2) If your project is upgraded from older version of Rails, you will need to perform the following steps.

(a) Add node_modules as one of the asset path. You can do this in initializers/assets.rb file:

Rails.application.config.assets.paths << Rails.root.join('node_modules')

(b) Add gitignore to prevent these js modules being versioned by Git.


(3) To add a module, use the yarn command in your rails root directory. E.g. adding momentjs module:

yarn add moment

(4) If you are running this for the first time, you will notice the following items are created.

- yarn.lock
- package.json
- node_modules [Directory]

The "yarn.lock" file is similar to Gemfile.lock which control the version of the js modules. The "package.json" is similar to "Gemfile". And finally a moment directory is created under node_modules.

(5) To upgrade the js modules to latest version in the future, you can use the upgrade command.

yarn upgrade

The other available yarn cli commands can be found here: https://yarnpkg.com/en/docs/cli/

(6) To use the module in your assets, you can add the following line in your js/coffee assets:

(js) //= require moment/moment
(coffee) #= require moment/moment

(7) Finally, if you are deploying your application by capistrano, you need to add support for yarn in order to download these js modules on your production servers.

(a) Include "capistrano-yarn" gem.

gem 'capistrano-yarn'

(b) Update Capfile with:

require 'capistrano/yarn'

(c) Install the Gem.

bundle install