San Diago
San Diago

Reputation: 1050

How to integrate gem using Webpacker instead of the asset pipeline? [Rails 6]

I want to use the local_time gem, but as per its installation instructions it should be included in the asset pipeline:

Installation

  1. Add gem 'local_time' to your Gemfile.

  2. Include local-time.js in your application's JavaScript bundle.

Using the asset pipeline:

//= require local-time

However, I'm using Webpacker and I can't figure out how to integrate the gem with it. Where should I include the line above? Or is it another strategy entirely?

Upvotes: 4

Views: 847

Answers (2)

Infinity Dev
Infinity Dev

Reputation: 21

1 Solution: install the rails-erb-loader, useful for embedding Ruby files in Javascript.

$ rails webpacker:install:erb

// packs/application.js //

Then if you have a gem that provides style sheets, you can import them as follows

import "<%= File.join(Gem.loaded_specs['yourgem'].full_gem_path, 'app', 'assets', 'stylesheets', 'yourfile.css') %>";

For Ruby gems with Javascript, how to import them can vary, but for many, it will be as simple as importing the files from the gem.

import "<%= File.join(Gem.loaded_specs['yourgem'].full_gem_path, 'app', 'assets', 'javascripts', 'yourfile') %>";

Upvotes: 2

San Diago
San Diago

Reputation: 1050

I think I got it working. I took a hint from the instructions for the local-time npm package mentioned in the link and added this to app\javascript\packs\application.js, before the other requires:

require("local-time").start()

Upvotes: 0

Related Questions