1

I'm trying to import the javascript from a gem's folder with Rails 6 webpacker. I've seen this only done with 1 file per import. Is it possible to grab all files with *.js extensions for a gem?

javascript/packs/application.js.erb

import "<%= File.read(File.join(Gem.loaded_specs['active_storage_drag_and_drop'].full_gem_path, 'lib', 'assets', 'javascripts', 'active_storage_drag_and_drop/*.js')) %>";

Error

(erb):17:in `read': No such file or directory @ rb_sysopen -/home/user.../active_storage_drag_and_drop../assets/javascript/active_storage_drag_and_drop/index.js

1 Answer 1

2

This package is available on NPM: https://www.npmjs.com/package/active_storage_drag_and_drop

I would instead do this:

yarn add active_storage_drag_and_drop

Then in your Webpack js file:

import * as ActiveStorageDragAndDrop from "active_storage_drag_and_drop"
window.ActiveStorageDragAndDrop = ActiveStorageDragAndDrop // needed as of v1.0.3

https://github.com/rossta/rails6-webpacker-demo/commit/ce1e8eb991b681574bdb7ce0ef33ae4e34b61dfd#diff-c0a98e77a42efd669302853444d5c362

I've created a working demo in a branch at https://github.com/rossta/rails6-webpacker-demo/tree/example/active_storage_drag_and_drop

Because the package's JS source makes assumptions about globals as of v1.0.3, assigning the imported var in your project JS appears to be necessary until the package is updated.

You may still need the gem in your Gemfile for the Ruby-based dependencies.

Generally, I would not recommend trying to look up javascript dependencies provided by Ruby gems via the gem path in ERB. One of the advantages of moving to Webpack/Webpacker is that you should try to leverage NPM for your dependencies where possible.

Sign up to request clarification or add additional context in comments.

6 Comments

It doesn't load all of the dependencies for active_storage_drag_and_drop. I tested it on Rails 6. You can try with a test project to see if you get any errors in the view when the component loads. It shows no animations, only the surface is clickable and you can add files without knowing if they've been attached.
It appears to include the exact JS provided by the gem: github.com/marinosoftware/active_storage_drag_and_drop/blob/…
Looks like the JS references a global variable. I'll update the answer with a workaround, but I'd otherwise consider this a bug in the activestorage_drag_and_drop project.
Holy sh*t, it works. I can't update vote. Someone else has to do it.
Thanks, can you mark the question as correct for others to see?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.