how to use npm packages in rails

Novice picture Novice · Apr 13, 2016 · Viewed 11.9k times · Source

I'm trying to use the Ace editor in my Ruby on Rails app, with majority of the view composed as React components. I'm using the react-rails gem and I'm not using flux at all.

I found this react-ace package, but I have to use npm to install it. I've been able to get bower components working with bower-rails gem but never got npm packages to work. Is there a way to use this just through the asset pipeline (through vendor)?

By the way, I'm not using browserify or ES6 so I don't even have import. I've been doing everything through the asset pipeline so far.

Thanks!

Answer

Gerard Simpson picture Gerard Simpson · Aug 7, 2018

To include npm packages in a rails project using the asset pipeline, do the following:

  1. Initialise your package.json: npm init

  2. Add node_modules to your asset path:

# config/application.rb
module YourApp
 class Application < Rails::Application
   config.assets.paths << Rails.root.join('node_modules')
 end
end

  1. Make sure npm install runs on startup by adding an initializer:
# config/initializers/npm.rb
system 'npm install' if Rails.env.development? || Rails.env.test?
  1. Install your package: npm install YourPackage

  2. Link to your package from app/assets/javascripts/application.js:

//= require /Path/To/YourPackage