The best way to load npm packages in Rails is to use npm as your pipeline itself. npm-pipeline-rails helps you do just that.
Don't want to switch away from the asset pipeline? That's fine, read on for an alternative approach.
node_modulesto your gitignore
Because you don't want to commit those, just like you don't commit your gems.
echo '/node_modules' >> .gitignore
package.jsonin your project
This is the npm equivalent of a
Gemfile—it's where your packages are stored.
node_modulesto your asset path
This lets you use npm modules in your Sprockets assets. In
module YourApp class Application < Rails::Application config.assets.paths << Rails.root.join('node_modules')
npm installon startup
Rails (or Bundler) prevents you from starting itself when you have gems that aren't installed yet. To emulate that behavior for npm packages, do this in
system 'npm install' if Rails.env.development? || Rails.env.test?
If you're deploying to Heroku, the default Ruby buildpack doesn't include Node, which you need to use npm. Add both the Node.js and Ruby buildpacks:
heroku buildpackse:add 'https://github.com/heroku/heroku-buildpack-nodejs.git' heroku buildpacks:add 'https://github.com/heroku/heroku-buildpack-ruby.git'
npm install with
--save to add packages.
npm install --save --save-exact modernizr
Then in your
application.js, require it like so:
//= require onmount/onmount