如何将config.assets.precompile用于目录而不是单个文件?

问题描述 投票:14回答:5

如何在生产中使用config.assets.precompile只包含'lib / assets / javascripts','lib / assets / stylesheets','vendor / assets / javascripts'和'vendor / assets / stylesheets'中的文件?

基本上是这样的:

config.assets.precompile += %w( pagespecific.js anotherpage.js )

但过去常常将文件包含在不是“app / assets / javascripts”或“app / assets / stylesheets”的特定目录中。

*编辑:添加我最终用于页面特定js的解决方案

config.assets.precompile += ['pages/*.js']
ruby-on-rails asset-pipeline
5个回答
27
投票

你可以这样写:

config.assets.precompile += ['directory/*']

3
投票

编译资产的目的是构建一个(或少量)文件,以最大限度地减少来自浏览器的HTTP请求数。

如果您要单独提供每个文件,那么为什么不禁用预编译?

要按预期使用预编译,请使用Sprockets的require_directory将整个目录构建到一个文件中:

//= require_directory ./awesome_js_app

...并在config.assets.precompile数组中列出该文件。

默认情况下,所有CSS都内置到application.css和JS中,并且内置到application.js中。您可以使用config/environments/production.rb中的预编译指令(以及其他env,如果您愿意)添加更多顶级文件进行编译。例如:

config.assets.precompile += %w( public.css public.js )

然后,那些顶级文件中的Sprockets //= require ...指令将确定最终编译文件的组成。

您可以在布局中使用这些额外的顶级文件,以便为某些视图使用不同的CSS和JS。


1
投票

将此作为资产路径包含它可能会好一些(根据您的示例解决方案):

config.assets.paths << Rails.root.join('app', 'assets', 'javascripts', 'pages')

它还允许您包含不在assets目录中的路径(例如,包括bootstrap-sass)。然后,这些路径将添加到公共目录中的assets文件夹中,如果使用asset_sync之类的内容,则会将其推送到资产位置。


0
投票

我找到了这个链接,想想可能对你有帮助,请看

keithgaputis的回答。 Rails config.assets.precompile setting to process all CSS and JS files in app/assets

我想你可以这样做。

# In production.rb
config.assets.precompile << Proc.new { |path|
  if path =~ /\.(css|js)\z/
    full_path = Rails.application.assets.resolve(path).to_path
    app_assets_path = Rails.root.join('app', 'assets').to_path
    if full_path.starts_with? app_assets_path
      puts "excluding asset: " + full_path
      false
    else
      puts "including asset: " + full_path
      true
    end
  else
    false
  end
}

0
投票

从Sprockets 3开始,您可以使用manifest.js文件来声明预编译了哪些文件或目录。见upgrade docs。所以在你的配置中你会添加:

config.assets.precompile = %w(manifest.js)

然后在app / assets / config / manifest.js中你可以拥有

//= link_directory ../pages .js

如果您希望预编译嵌套子目录中的js文件,请使用link_tree

© www.soinside.com 2019 - 2024. All rights reserved.