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

如何在生产中使用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'] 

你可以这样写:

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

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

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

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

 //= require_directory ./awesome_js_app 

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

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

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

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

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

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

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

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

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

keithgaputis的回答。 Rails config.assets.precompile设置用于处理app / assets中的所有CSS和JS文件

我想你可以这样做。

 # 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 } 

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

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

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

 //= link_directory ../pages .js 

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