【问题标题】:Why external javascript file not working Rails 6?为什么外部 javascript 文件在 Rails 6 中不起作用?
【发布时间】:2020-10-15 13:43:13
【问题描述】:

我正在使用 Ruby on Rails 6,我正在尝试将自定义 javascript 文件移动到外部文件,但它无法正常工作。如果我将代码移动到 erb 文件,Javascript 代码就可以工作。你能帮帮我吗?

这是 index.html.erb (app/views/home/index.html.erb)

<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>
<i class="fab fa-twitter"></i>
<i class="fas fa-home"> </i>

<button id="target" value="submit">Submit</button>

<script>
 // this code is working if i put inside .erb file
 /* $( "#target" ).click(function() {alert( "Testing" );}); */
</script>

这是 custom.js (app/javascript/packs/custom.js)

console.log("File loaded");
$( "#target" ).click(function() {
    alert( "Testing" );
});

这是我的 application.js (app/javascript/packs/application.js)

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('jquery')
require("packs/custom")

这是我的 environment.js (app/config/webpack/environment.js)

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery'
    })
)

module.exports = environment

【问题讨论】:

  • 您使用什么环境来运行应用程序? (开发/生产)

标签: javascript jquery ruby ruby-on-rails-6


【解决方案1】:

确保您在开发模式下运行您的应用程序:

rails s -e development

如果您在生产模式下运行它,请确保在此之前运行它:

RAILS_ENV=production bundle exec rails webpacker:compile

您还可以选择仅包含特定视图的 .js 文件。 在 index.html.erb 你可以添加:

<%= javascript_include_tag "custom", "data-turbolinks-track" => true  %>

【讨论】:

    【解决方案2】:

    你应该替换它。 true %>

    这将查看您的包,而 include 将查看您的资产文件夹。

    【讨论】:

      【解决方案3】:

      我知道已经晚了,但我遇到了完全相同的问题,我修复了它并添加:

      jQuery(() => {
         //Your js goes here
      })
      

      或等效的$(document).ready(() =&gt;{})

      这是因为 Turbolinks 不兼容。还有其他解决方法,但现在这在我的案例中成为了窍门。

      【讨论】:

        猜你喜欢
        • 2021-01-06
        • 2021-08-12
        • 2021-02-15
        • 2013-02-06
        • 1970-01-01
        • 2012-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多