为啥我的 RoR 应用程序中的 CSS 会根据我是在生产还是开发中运行而发生变化?

Posted

技术标签:

【中文标题】为啥我的 RoR 应用程序中的 CSS 会根据我是在生产还是开发中运行而发生变化?【英文标题】:Why does the CSS change in my RoR app depending on whether I run it in production or development?为什么我的 RoR 应用程序中的 CSS 会根据我是在生产还是开发中运行而发生变化? 【发布时间】:2021-09-05 04:14:48 【问题描述】:

我在生产中运行时遇到了一些在开发中不存在的问题,例如,我有一个下拉菜单,在开发中运行时看起来与我预期的一样:只有菜单按钮可见,并且它下面的选项在悬停或聚焦之前是隐藏的。也没有要点。但是,当我在生产环境中运行时,我会在每个 <li> 上获得项目符号,而我之前隐藏的选项现在在我的菜单 <button> 下方显示得很乱。

html

<nav class="dropdown-nav" role="navigation">
  <ul class="main-menu">
    <li>
      <button class="btn btn--action" aria-haspopup="true"><%= t('menu') %></button>
      <ul class="dropdown" aria-label="submenu">
        <% if logged_in? %>
          ....
        <% else %>
          <li class="nav-item">
            <%= link_to(t('signup'), signup_path) %>
          </li>
          <li class="nav-item">
            <%= link_to(t('login'), login_path) %>
          </li>
        <% end %>
      </ul>
    </li>
  </ul>
</nav>

scss:

.main-menu 
  padding: 0;
  list-style-type: none;
  
  & li 
    display: block;
    transition-duration: 0.5s;

    &:hover,
    &:focus-within 
      cursor: pointer;
    

    &:hover > ul,
    &:focus-within > ul,
    & ul:hover,
    & ul:focus 
      visibility: visible;
      opacity: 1;
      display: block;
    
  


.dropdown 
  visibility: hidden;
  opacity: 0;
  position: absolute;
  transition: all 0.5s ease;
  display: none;

  padding: 0.2rem;
  background-color: $off-white;
  min-width: 10rem;
  box-shadow: 0px 10px 10px -5px;
  z-index: 1;
  overflow: auto;
  margin-top: 0;
  list-style-type: none;


.nav-item 
  clear: both;
  padding: 0.5rem 1rem;

  &:hover,
  &:focus-within 
    cursor: pointer;
  

编辑以添加我的 config/environments/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 = false

  # 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 = false

  # `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 = "Appear_#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

【问题讨论】:

很可能,您正在使用多个 CSS 文件,但只有一些正在加载。您可以使用 Inspector 查看生产中是否缺少 CSS 文件吗?还是在 dev 中定义了“丢失”的规则? 【参考方案1】:

你使用 sass ampersand 错误。

.main-menu 
  &:li 
    display: block;
    transition-duration: 0.5s;
    ...
  

编译为:

li.main-menu 
  display: block;
  transition-duration: 0.5s;
  ...

随心所欲:

.main-menu li
  display: block;
  transition-duration: 0.5s;
  ...

如果你只删除 & 符号,你会得到:

.main-menu 
  padding: 0;
  list-style-type: none;
  li 
    display: block;
    transition-duration: 0.5s;

    &:hover,
    &:focus-within 
      cursor: pointer;
    

    &:hover > ul,
    &:focus-within > ul,
    ul:hover,
    ul:focus 
      visibility: visible;
      opacity: 1;
      display: block;
    
  

当您想将规则添加到当前选择器时,请使用与号。使用常规嵌套来定义子元素的规则。

【讨论】:

我并不想详细说明为什么它会在本地运行而不是在生产环境中运行,但我猜你运行的代码不一样。 非常感谢你是绝对正确的,我在 apersand 上犯了一个错误,但现在已经改变它以符合你的建议,问题仍然存在。 嗯,这个问题的答案要复杂得多,只能通过您的调试工作才能真正解决。您需要确保生产服务器实际上提供相同的 CSS,并且不是由于代码奇偶校验问题或资产编译失败。

以上是关于为啥我的 RoR 应用程序中的 CSS 会根据我是在生产还是开发中运行而发生变化?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 CSS 中的边距/填充百分比总是根据宽度计算?

RoR:加载编辑页面时根据用户选择显示/隐藏字段?

为啥我的 CSS 动画会消耗这么多资源?

RoR - 我的一个控制器中的视图无缘无故地不显示应用程序布局

为啥 w3.css Side navbar 在我的页面上不起作用?

为啥 shinyFeedback 会覆盖自定义 CSS?