Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use config.assets.precompile for directories rather than single files?

How do I use config.assets.precompile in production to only include the files in 'lib/assets/javascripts', 'lib/assets/stylesheets', 'vendor/assets/javascripts' and 'vendor/assets/stylesheets'?

Basically something like:

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

But used to auto include files in specific directories that are not 'app/assets/javascripts' or 'app/assets/stylesheets'.

*edit: adding the solution I ended up using for page specific js

config.assets.precompile += ['pages/*.js']
like image 569
eddywashere Avatar asked Sep 27 '12 04:09

eddywashere


People also ask

How do you Precompile an asset?

To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.

What does rake assets Precompile do?

rake assets:precompile. We use rake assets:precompile to precompile our assets before pushing code to production. This command precompiles assets and places them under the public/assets directory in our Rails application.

What is Require_tree?

The require_tree directive tells Sprockets to recursively include all JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file.


2 Answers

You can simply write it like this:

config.assets.precompile += ['directory/*']
like image 132
zolter Avatar answered Oct 18 '22 11:10

zolter


The point of compiling assets is to build one (or a small number of) files to minimize the number of HTTP requests from the browser.

If you're going to serve each file individually, then why not just disable precompile?

To use precompile as intended, build an entire directory into one file using Sprockets' require_directory:

//= require_directory ./awesome_js_app

...and list that file in your config.assets.precompile array.

By default, all CSS is built into application.css & JS into application.js. You can add more top-level files to compile with the precompile directive in config/environments/production.rb (and other envs if you wish.) For example:

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

Then the Sprockets //= require ... directives in those top-level files will determine the composition of final compiled file.

You can use these additional top-level files in your layouts to have different CSS & JS for certain views.

like image 30
Mars Avatar answered Oct 18 '22 11:10

Mars