【问题标题】:Javascript not loading on herokuJavascript未在heroku上加载
【发布时间】:2017-12-29 07:51:37
【问题描述】:

我正在尝试部署一个应用程序。我的 javascript 在开发中完美加载,但在生产中没有加载。即使我在生产中也没有遇到任何错误。如果有人需要更多信息,请告诉我。
我已经尝试过以下命令

heroku 运行 rake 资产:precompile --app my_app

我也尝试过 alert() 函数,它也不适用于 heroku。

<script type="text/javascript">
            $(function() {
                $(document).ready(function() {
                    $('.flexslider').flexslider({
                        animation: "fade",
                        slideshowSpeed: 4000,
                        animationSpeed: 600,
                        controlNav: false,
                        directionNav: true,
                        controlsContainer: ".flex-container" // the container that holds the flexslider
                    });
                });
            });
        </script>

宝石文件

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.5'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development


group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Gemfile.lock

GEM
  remote: https://rubygems.org/
  specs:
    actioncable (5.0.6)
      actionpack (= 5.0.6)
      nio4r (>= 1.2, < 3.0)
      websocket-driver (~> 0.6.1)
    actionmailer (5.0.6)
      actionpack (= 5.0.6)
      actionview (= 5.0.6)
      activejob (= 5.0.6)
      mail (~> 2.5, >= 2.5.4)
      rails-dom-testing (~> 2.0)
    actionpack (5.0.6)
      actionview (= 5.0.6)
      activesupport (= 5.0.6)
      rack (~> 2.0)
      rack-test (~> 0.6.3)
      rails-dom-testing (~> 2.0)
      rails-html-sanitizer (~> 1.0, >= 1.0.2)
    actionview (5.0.6)
      activesupport (= 5.0.6)
      builder (~> 3.1)
      erubis (~> 2.7.0)
      rails-dom-testing (~> 2.0)
      rails-html-sanitizer (~> 1.0, >= 1.0.3)
    activejob (5.0.6)
      activesupport (= 5.0.6)
      globalid (>= 0.3.6)
    activemodel (5.0.6)
      activesupport (= 5.0.6)
    activerecord (5.0.6)
      activemodel (= 5.0.6)
      activesupport (= 5.0.6)
      arel (~> 7.0)
    activesupport (5.0.6)
      concurrent-ruby (~> 1.0, >= 1.0.2)
      i18n (~> 0.7)
      minitest (~> 5.1)
      tzinfo (~> 1.1)
    addressable (2.5.2)
      public_suffix (>= 2.0.2, < 4.0)
    arel (7.1.4)
    bindex (0.5.0)
    builder (3.2.3)
    byebug (9.1.0)
    capybara (2.16.1)
      addressable
      mini_mime (>= 0.1.3)
      nokogiri (>= 1.3.3)
      rack (>= 1.0.0)
      rack-test (>= 0.5.4)
      xpath (~> 2.0)
    childprocess (0.8.0)
      ffi (~> 1.0, >= 1.0.11)
    coffee-rails (4.2.2)
      coffee-script (>= 2.2.0)
      railties (>= 4.0.0)
    coffee-script (2.4.1)
      coffee-script-source
      execjs
    coffee-script-source (1.12.2)
    concurrent-ruby (1.0.5)
    crass (1.0.3)
    erubis (2.7.0)
    execjs (2.7.0)
    ffi (1.9.18)
    globalid (0.4.1)
      activesupport (>= 4.2.0)
    i18n (0.9.1)
      concurrent-ruby (~> 1.0)
    jbuilder (2.7.0)
      activesupport (>= 4.2.0)
      multi_json (>= 1.2)
    jquery-rails (4.3.1)
      rails-dom-testing (>= 1, < 3)
      railties (>= 4.2.0)
      thor (>= 0.14, < 2.0)
    listen (3.1.5)
      rb-fsevent (~> 0.9, >= 0.9.4)
      rb-inotify (~> 0.9, >= 0.9.7)
      ruby_dep (~> 1.2)
    loofah (2.1.1)
      crass (~> 1.0.2)
      nokogiri (>= 1.5.9)
    mail (2.7.0)
      mini_mime (>= 0.1.1)
    method_source (0.9.0)
    mini_mime (1.0.0)
    mini_portile2 (2.3.0)
    minitest (5.10.3)
    multi_json (1.12.2)
    nio4r (2.2.0)
    nokogiri (1.8.1)
      mini_portile2 (~> 2.3.0)
    pg (0.21.0)
    public_suffix (3.0.1)
    puma (3.11.0)
    rack (2.0.3)
    rack-test (0.6.3)
      rack (>= 1.0)
    rails (5.0.6)
      actioncable (= 5.0.6)
      actionmailer (= 5.0.6)
      actionpack (= 5.0.6)
      actionview (= 5.0.6)
      activejob (= 5.0.6)
      activemodel (= 5.0.6)
      activerecord (= 5.0.6)
      activesupport (= 5.0.6)
      bundler (>= 1.3.0)
      railties (= 5.0.6)
      sprockets-rails (>= 2.0.0)
    rails-dom-testing (2.0.3)
      activesupport (>= 4.2.0)
      nokogiri (>= 1.6)
    rails-html-sanitizer (1.0.3)
      loofah (~> 2.0)
    railties (5.0.6)
      actionpack (= 5.0.6)
      activesupport (= 5.0.6)
      method_source
      rake (>= 0.8.7)
      thor (>= 0.18.1, < 2.0)
    rake (12.3.0)
    rb-fsevent (0.10.2)
    rb-inotify (0.9.10)
      ffi (>= 0.5.0, < 2)
    ruby_dep (1.5.0)
    rubyzip (1.2.1)
    sass (3.5.4)
      sass-listen (~> 4.0.0)
    sass-listen (4.0.0)
      rb-fsevent (~> 0.9, >= 0.9.4)
      rb-inotify (~> 0.9, >= 0.9.7)
    sass-rails (5.0.7)
      railties (>= 4.0.0, < 6)
      sass (~> 3.1)
      sprockets (>= 2.8, < 4.0)
      sprockets-rails (>= 2.0, < 4.0)
      tilt (>= 1.1, < 3)
    selenium-webdriver (3.8.0)
      childprocess (~> 0.5)
      rubyzip (~> 1.0)
    spring (2.0.2)
      activesupport (>= 4.2)
    spring-watcher-listen (2.0.1)
      listen (>= 2.7, < 4.0)
      spring (>= 1.2, < 3.0)
    sprockets (3.7.1)
      concurrent-ruby (~> 1.0)
      rack (> 1, < 3)
    sprockets-rails (3.2.1)
      actionpack (>= 4.0)
      activesupport (>= 4.0)
      sprockets (>= 3.0.0)
    thor (0.20.0)
    thread_safe (0.3.6)
    tilt (2.0.8)
    turbolinks (5.0.1)
      turbolinks-source (~> 5)
    turbolinks-source (5.0.3)
    tzinfo (1.2.4)
      thread_safe (~> 0.1)
    uglifier (4.0.2)
      execjs (>= 0.3.0, < 3)
    web-console (3.5.1)
      actionview (>= 5.0)
      activemodel (>= 5.0)
      bindex (>= 0.4.0)
      railties (>= 5.0)
    websocket-driver (0.6.5)
      websocket-extensions (>= 0.1.0)
    websocket-extensions (0.1.3)
    xpath (2.1.0)
      nokogiri (~> 1.3)

PLATFORMS
  ruby

DEPENDENCIES
  byebug
  capybara (~> 2.13)
  coffee-rails (~> 4.2)
  jbuilder (~> 2.5)
  jquery-rails
  listen (>= 3.0.5, < 3.2)
  pg (~> 0.18)
  puma (~> 3.7)
  rails (~> 5.0.5)
  sass-rails (~> 5.0)
  selenium-webdriver
  spring
  spring-watcher-listen (~> 2.0.0)
  turbolinks (~> 5)
  tzinfo-data
  uglifier (>= 1.3.0)
  web-console (>= 3.3.0)

BUNDLED WITH
   1.15.4

production.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Attempt to read encrypted secrets from `config/secrets.yml.enc`.
  # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
  # `config/secrets.yml.key`. 
  config.read_encrypted_secrets = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true
  config.serve_static_assets = true

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Mount Action Cable outside main process or domain
  # config.action_cable.mount_path = nil
  # config.action_cable.url = 'wss://example.com/cable'
  # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level = :debug

  # Prepend all log lines with the following tags.
  config.log_tags = [ :request_id ]

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Use a real queuing backend for Active Job (and separate queues per environment)
  # config.active_job.queue_adapter     = :resque
  # config.active_job.queue_name_prefix = "my_bagicha_#{Rails.env}"
  config.action_mailer.perform_caching = false

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Use a different logger for distributed setups.
  # require 'syslog/logger'
  # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')

  if ENV["RAILS_LOG_TO_STDOUT"].present?
    logger           = ActiveSupport::Logger.new(STDOUT)
    logger.formatter = config.log_formatter
    config.logger    = ActiveSupport::TaggedLogging.new(logger)
  end

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false
end

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

【问题讨论】:

    标签: javascript ruby-on-rails ruby heroku ruby-on-rails-5


    【解决方案1】:

    您需要删除 require_tree 并以这种方式加载您的 js。

    //= require jquery
    //= require jquery.flexslider-min
    //= require jquery_ujs
    

    【讨论】:

      【解决方案2】:

      适用于 Rails 6+(或使用 Webpacker 的)

      如果您刚刚为 Heroku 部署了一个新开发的 Rails 应用程序,即 Hobby 层或类似的东西,那么您需要确保您已添加到 Node 构建包:

      (1) 确保您的 heroku 遥控器已设置:

      • 以下假设 heroku 是 git 远程的名称。您可以通过输入以下内容来检查您是否已设置:

      git remote -v

      ...您应该会在此处看到 heroku。如果看不到,则需要设置一个git远程指向heroku。

      (2) 添加NodeJS Buildpack

      • 这将清除构建包 - 如果您不想消除其他构建包,请不要这样做:

      heroku buildpacks:clear

      • 首先添加 nodejs buildpack(注意:这里的顺序很重要:ruby 必须在 nodejs 之后)

      heroku buildpacks:set heroku/nodejs
      heroku buildpacks:add heroku/ruby

      (3) 最后,检查您是否正确地为您的资产服务:

      就我而言,我使用的是style_sheet_pack_tag

      # application.html.erb
      <%= stylesheet_pack_tag "application", media: 'all', 'data-turbolinks-track': 'reload' %>
      

      希望这对某人有所帮助!

      【讨论】:

        【解决方案3】:

        在控制台查看错误是什么

        如果您使用任何 jquery 库,则使用 jquery-rails 实现 Gemfile,如下所示

        # Use jquery as the JavaScript library
        gem 'jquery-rails'
        

        然后安装包

        然后更新application.js

        //= require jquery
        

        如果您的应用使用turbolinks,请修改您的代码,如下所示

        $(document).on('turbolinks:load', function(){
          $('.flexslider').flexslider({
            animation: "fade",
            slideshowSpeed: 4000,
            animationSpeed: 600,
            controlNav: false,
            directionNav: true,
            controlsContainer: ".flex-container" // the container that holds the flexslider
          });
        });
        

        希望能帮到你

        【讨论】:

        • @ankur 检查您的浏览器控制台并检查错误,然后输入您的错误
        • @fool- Uncaught ReferenceError: $ is not defined
        • 嗨,@ankur:在您的 application.js 中也许您还需要添加“//= require turbolinks”,您在 application.html.erb 中有 stylesheet_link_tag 吗?
        • @Pietro Allievi - 我不需要添加 turbolinks,因为我没有使用任何 turbolinks 功能
        • ok @ankur 这是 jquery 没有找到错误你可以尝试不同的方式 google.com/…
        【解决方案4】:

        rails-ujs,在 Rails 5 中引入,不是为了使用 jQuery - 它是为了摆脱 jQuery 依赖而开发的。

        所以,如果你还需要jQuery,你需要有如下设置:

        宝石文件: gem 'jquery-rails'

        应用程序.js: //= require jquery //= require jquery_ujs

        如果application.js 中已经存在//= require rails-ujs,则删除它。

        【讨论】:

        • 它仍然无法进行生产。我已经更新了我的问题
        • 我仍然可以在您的 Gemfile 中看到 gem 'rails-ujs', '~&gt; 5.1.0.beta1' 行。应该改为gem 'jquery-rails'
        • 我已删除 rails-ujs 仍然无法正常工作。另外,我更新了我的 Gemfile 并添加了 Gemfile.lock。如果您需要更多信息,请告诉我
        • 我想到的最后一个想法是在预编译资产之前尝试清理资产,同时使用 bundle exec ``` heroku run bundle exec rake assets:clean heroku run bundle 运行资产任务exec rake assets:precompile ```
        • 这对我来说是正确的答案。 Rails 5 有 rails-ujs,它本质上是 jquery-ujs(没有 Jquery lol).. 所以使用 Rails 5;如果在任何地方使用 Jquery,你仍然需要 jquery-rails gem。我添加了 gem,添加 //= require jquery 作为 application.js 中的第一行并保留 //= require rails-ujs,删除 gemlock 并捆绑安装,推送到 heroku.. 一切都很好!
        猜你喜欢
        • 2016-02-18
        • 1970-01-01
        • 2015-11-12
        • 1970-01-01
        • 1970-01-01
        • 2017-05-28
        • 2021-12-08
        • 1970-01-01
        • 2013-11-20
        相关资源
        最近更新 更多