10

我想從application.js中創建一個自定義清單javascript文件。我從application.js中獲取代碼並將其粘貼到一個新文件中,該文件稱爲「other_manifest.js」,並放置在assets/javascrips目錄中。下面是代碼:Rails資產管道:如何創建自定義清單文件

// 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, vendor/assets/javascripts, 
// or vendor/assets/javascripts of plugins, if any, 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. 
// 
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details 
// about supported directives. 
// 
//= require jquery 
//= require jquery_ujs 
//= require turbolinks 
//= require bootstrap 
//= require_tree . 

在我assets.rb文件,我已經包含行:

Rails.application.config.assets.precompile += %w(other_manifest.js) 

我預編譯和局部清理資產,然後當我運行該頁面,所有我得到的是清單文件中的確切文本。它沒有引入任何文件。我如何創建自定義清單文件?

+0

你在app/views/layouts/application.html文件中替換了'application.js'嗎? – itsnikolay

+0

我放入一個if/else,這取決於頁面,application.js顯示或other_manifest.js顯示 – Philip7899

回答

2

很容易

您有application.js。創建第二個文件:在佈局layouts/application.html.erbother_manifest.js

然後(可能是一個不同的佈局完全):

<% if condition %> 
    <%= javascript_include_tag 'other_manifest' %> 
<% else %> 
    <%= javascript_include_tag 'application' %> 
<% end %> 

是的,你需要在你的config/initializers/assets.rb(其次是重新啓動)地址:

Rails.application.config.assets.precompile += %w(other_manifest.js) 

此外,請確保從清單中刪除//= require_tree .。因爲它將包括清單中的所有JavaScript(使得具有不同的清單毫無意義)

相關問題