how to use npm packages in rails

て烟熏妆下的殇ゞ 提交于 2019-12-10 13:39:29

问题


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!


回答1:


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:

    module YourApp class Application < Rails::Application config.assets.paths << Rails.root.join('node_modules')

  3. Make sure npm install runs on startup:

    In config/initializers/npm.rb:

    system 'npm install' if Rails.env.development? || Rails.env.test?

  4. Install your package:

    npm install YourPackage

  5. Link to your package from application.js

    //= require /Path/To/YourPackage




回答2:


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.



来源:https://stackoverflow.com/questions/36602764/how-to-use-npm-packages-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!