1

I'm trying to create a plugin which is suppose to expose a javascript file, but I can't get it to load in my rails 5 application.

In my gem, I've tried adding my javascript file called my_gem.js to

  • vendor/assets/javascripts
  • app/assets/javascripts
  • lib/<gem-name>/assets/javascripts

But none of them work. I just get this error message when loading the file in my application.js

couldn't find file 'my_gem' with type 'application/javascript'

This is how I load my plugin/gem in to my rails project

gem "my-gem", path: "~/projects/my-gem"

2 Answers 2

1

We've created a gem which utilizes assets before.

You'll want to create an app/assets/javascripts/my_gem folder in your gem directory tree, where you'll put your my_gem.js file.

Most importantly, you need to add this file to the asset path (we use an engine):

#lib/my_gem.rb
module MyGem
   class Gem < Rails::Engine
      config.assets.precompile += %w(my_gem/my_gem.js) 
   end
end

This will either allow the file to be used standalone, or as part of your app:

#app/assets/javascripts/application.js
//= require my_gem/my_gem
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Almost correct. Adding config.assets.precompile += %w(gem/file.js) to the engine.rb exposes the file.js file meaning that //= require file should used, not //= require gem/file.
1

You must tell Rails to compile my_gem.js. You can do this in an initializer, application.rb, or environment file.

  Rails.application.config.assets.precompile += ["my_gem.js"]

I'd recommend keeping the source file at ~/projects/my-gem/app/assets/javascripts/my_gem.js

6 Comments

I upvoted although the above code needs to be in the gem, not the app ;)
An initializer can be in the gem
Yes of course; I thought your answer was ambiguous on the point though
Here is information about adding an initializer in your gem (assuming it is a Rails Engine) link
ah, OK. Thanks for clarifying
|

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.