How to use npm packages in rails? How to use npm packages in rails? reactjs reactjs

How to use npm packages in rails?


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.rbmodule YourApp class Application < Rails::Application   config.assets.paths << Rails.root.join('node_modules') endend
  1. Make sure npm install runs on startup by adding an initializer:
# config/initializers/npm.rbsystem '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


The short answer is that the ACE editor was built to run in Node.js not Rails, so there's no simple way to do this. Remember that most npm packages are intended to be used as server-side javascript with running on the Node.js environment and wont be runnable directly within Ruby. I believe th Ace Editor requires a Node.js backend and I doubt it would be trivial to have it run in a Rails backend.

Of course, any javascript which runs in the browser can be integrated the Rails asset pipeline. Towards this end I recommend checking out Bower, which is the most commonly used package management system (http://bower.io). You can install directly within your Rails application, though I'd recommend checking out Bower rails for better integration with Rails conventions and the asset pipeline https://github.com/rharriso/bower-rails.

If you want to try porting platform-agnostic javascript to the browser you can check out browserify, which simply links javascript files using the CommonJS require format that Node.js uses. It won't magically make server-side javascript frameworks like Express or the ACE Editor work solely in the browser, however.


Rails 5.1 supports including npm packages using Yarn.

For example, let’s say we want to use the moment.js library. We need first of all install the library using Yarn:

yarn add moment

We can see that package.json was updated:

{  "name": "yarn_test",  "private": true,  "dependencies": {    "moment": "^2.18.1"  }}

And finally we need to include the new package to application.js:

//= require moment/moment

See Rails 5.1 and forward - Part 1: Yarn on Rails