Milos
Milos

Reputation: 1263

What's the best way to run npm packages on Rails?

I'm new to rails and am using React for the front end. Ideally I would love to be able to go into my component and at the top, place an import statement like:

import npmpackage from 'npm-package'

It seems I cannot do that, and always get some kind of an error from rails when i try to run the server. I've heard the rails version that I'm using (5.1.3) allows for use of webpack, es6, and import statements like this.

Can anyone explain to me or maybe link me to a good guide on how this is done? Google seems to link me to unhelpful guides or outdated ones that use rails 4 or earlier.

this is my application.rb file:

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Mediumrails
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.assets.paths << Rails.root.join('node_modules');
    config.load_defaults 5.1


    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
  end
end

Upvotes: 0

Views: 1385

Answers (1)

rony36
rony36

Reputation: 3339

How about (In Rails 5.1+):

rails new my-react-rails-app webpack=react

Or add gem 'webpacker' to Gemfile and bundle it. And then run ./bin/rails webpacker:install:react And just sit tight to give some time to rails to prepare everything :)

Maybe this post could be helpful.

Cheers!

Upvotes: 1

Related Questions