简体   繁体   中英

Rails asset pipeline require from public folder?

Is this a good practice to require assets located under public folder? eg I have lots of javascript under public/mythirdparyjs folder and I want to make these javascript files available for only specific page, what will be the best way to do this?

Thirdparty js files should be in your vendor folder. Once you precompile them for production they will be then moved into your public folder automagically. To call certain files on specific pages you need to remove the require_tree directive and also pay attention to which files are called in your application.js asset file. At the bottom of every view page (html.erb) you can add the following to run only page specific js:

<%= content_for :javascript do %>
  <script type='text/javascript'>
    YOUR FUNCTIONS HERE
  </script>
<% end %>

Then in your application/layout view at the bottom before the closing body tag you should add:

<%= javascript_include_tag params[:controller] if Rails.application.assets_manifest.assets["#{params[:controller]}.js"] %>
<%=yield :javascript %>

This will then run any js on a page by page view basis and include any require statements for any files in the corresponding controller's js asset file.

UPDATE to address comment: If you have a gem you installed and then need to require certain js files, these should be required from your app/assets/javascripts folder in either the application.js file (if you want that gem to be usable throughout your application) or in the controller specific js file if you only need that functionality on a few pages. For example, the angular gem is probably used throughout your application so you would add the //=require statement to the application.js file in your app/assets/javascripts folder. If you manually download some js libraries you should put them in the vendor/javascripts folder however you still require them in your app/assets/javascripts folder files wherever needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM