简体   繁体   English

如何从Rails插件加载JavaScript文件

[英]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. 我正在尝试创建一个插件,该插件应该公开一个javascript文件,但无法在Rails 5应用程序中加载它。

In my gem, I've tried adding my javascript file called my_gem.js to 在我的gem中,我尝试将名为my_gem.js javascript文件添加到

  • 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 将文件加载到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加载到我的rails项目中的方式

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

You must tell Rails to compile my_gem.js. 您必须告诉Rails编译my_gem.js。 You can do this in an initializer, application.rb, or environment file. 您可以在初始化程序,application.rb或环境文件中执行此操作。

  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 我建议将源文件保存在~/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. 您将要在gem目录树中创建一个app/assets/javascripts/my_gem文件夹,在其中放置my_gem.js文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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