简体   繁体   中英

How to load javascript file from rails plugin

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"

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM