asset_pipeline.md 41.3 KB
Newer Older
S
Steve Klabnik 已提交
1 2
The Asset Pipeline
==================
3

4
This guide covers the asset pipeline.
5 6

After reading this guide, you will know:
7

8
* What the asset pipeline is and what it does.
9
* How to properly organize your application assets.
10
* The benefits of the asset pipeline.
11 12
* How to add a pre-processor to the pipeline.
* How to package assets with a gem.
13 14 15 16 17 18

--------------------------------------------------------------------------------

What is the Asset Pipeline?
---------------------------

19 20 21
The asset pipeline provides a framework to concatenate and minify or compress
JavaScript and CSS assets. It also adds the ability to write these assets in
other languages and pre-processors such as CoffeeScript, Sass and ERB.
22

23 24 25
The asset pipeline is technically no longer a core feature of Rails 4, it has
been extracted out of the framework into the
[sprockets-rails](https://github.com/rails/sprockets-rails) gem.
26

27 28 29 30 31 32 33 34 35 36 37
The asset pipeline is enabled by default.

You can disable the asset pipeline while creating a new application by 
passing the `--skip-sprockets` option.

```bash
rails new appname --skip-sprockets
```

Rails 4 automatically adds the `sass-rails`, `coffee-rails` and `uglifier` 
gems to your Gemfile, which are used by Sprockets for asset compression:
38 39

```ruby
40 41 42
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
43 44
```

45 46 47 48 49 50 51
Using the `--skip-sprockets` option will prevent Rails 4 from adding 
`sass-rails` and `uglifier` to Gemfile, so if you later want to enable
the asset pipeline you will have to add those gems to your Gemfile. Also,
creating an application with the `--skip-sprockets` option will generate
a slightly different `config/application.rb` file, with a require statement
for the sprockets railtie that is commented-out. You will have to remove
the comment operator on that line to later enable the asset pipeline:
52

53 54
```ruby
# require "sprockets/railtie"
55 56
```

57 58 59
To set asset compression methods, set the appropriate configuration options 
in `production.rb` - `config.assets.css_compressor` for your CSS and
`config.assets.js_compressor` for your Javascript:
60

61 62 63 64
```ruby
config.assets.css_compressor = :yui
config.assets.js_compressor = :uglify
```
65

66 67
NOTE: The `sass-rails` gem is automatically used for CSS compression if included
in Gemfile and no `config.assets.css_compressor` option is set.
68 69


70
### Main Features
71

72 73 74 75
The first feature of the pipeline is to concatenate assets, which can reduce the
number of requests that a browser makes to render a web page. Web browsers are
limited in the number of requests that they can make in parallel, so fewer
requests can mean faster loading for your application.
76

77 78 79 80 81 82
Sprockets concatenates all JavaScript files into one master `.js` file and all
CSS files into one master `.css` file. As you'll learn later in this guide, you
can customize this strategy to group files any way you like. In production,
Rails inserts an MD5 fingerprint into each filename so that the file is cached
by the web browser. You can invalidate the cache by altering this fingerprint,
which happens automatically whenever you change the file contents.
83

84 85 86 87 88 89 90 91 92
The second feature of the asset pipeline is asset minification or compression.
For CSS files, this is done by removing whitespace and comments. For JavaScript,
more complex processes can be applied. You can choose from a set of built in
options or specify your own.

The third feature of the asset pipeline is it allows coding assets via a
higher-level language, with precompilation down to the actual assets. Supported
languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by
default.
93 94 95

### What is Fingerprinting and Why Should I Care?

96 97 98 99 100
Fingerprinting is a technique that makes the name of a file dependent on the
contents of the file. When the file contents change, the filename is also
changed. For content that is static or infrequently changed, this provides an
easy way to tell whether two versions of a file are identical, even across
different servers or deployment dates.
101

102 103 104 105 106
When a filename is unique and based on its content, HTTP headers can be set to
encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment,
or in web browsers) to keep their own copy of the content. When the content is
updated, the fingerprint will change. This will cause the remote clients to
request a new copy of the content. This is generally known as _cache busting_.
107

108 109
The technique sprockets uses for fingerprinting is to insert a hash of the
content into the name, usually at the end. For example a CSS file `global.css`
110 111 112 113 114 115 116

```
global-908e25f4bf641868d8683022a5b62f54.css
```

This is the strategy adopted by the Rails asset pipeline.

117 118
Rails' old strategy was to append a date-based query string to every asset linked
with a built-in helper. In the source the generated code looked like this:
119 120 121 122 123 124 125

```
/stylesheets/global.css?1309495796
```

The query string strategy has several disadvantages:

126 127 128 129 130 131
1. **Not all caches will reliably cache content where the filename only differs by
query parameters**<br>
    [Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/),
 "...avoiding a querystring for cacheable resources". He found that in this
case 5-20% of requests will not be cached. Query strings in particular do not
work at all with some CDNs for cache invalidation.
132

B
blahedo 已提交
133
2. **The file name can change between nodes in multi-server environments.**<br>
134 135 136 137 138
    The default query string in Rails 2.x is based on the modification time of
the files. When assets are deployed to a cluster, there is no guarantee that the
timestamps will be the same, resulting in different values being used depending
on which server handles the request.

B
blahedo 已提交
139
3. **Too much cache invalidation**<br>
140 141 142
    When static assets are deployed with each new release of code, the mtime
(time of last modification) of _all_ these files changes, forcing all remote
clients to fetch them again, even when the content of those assets has not changed.
143

144 145
Fingerprinting fixes these problems by avoiding query strings, and by ensuring
that filenames are consistent based on their content.
146

147 148 149
Fingerprinting is enabled by default for production and disabled for all other
environments. You can enable or disable it in your configuration through the
`config.assets.digest` option.
150 151 152 153

More reading:

* [Optimize caching](http://code.google.com/speed/page-speed/docs/caching.html)
154
* [Revving Filenames: don't use
155
* querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/)
156 157 158 159 160


How to Use the Asset Pipeline
-----------------------------

161 162 163 164
In previous versions of Rails, all assets were located in subdirectories of
`public` such as `images`, `javascripts` and `stylesheets`. With the asset
pipeline, the preferred location for these assets is now the `app/assets`
directory. Files in this directory are served by the Sprockets middleware.
165

166 167 168 169
Assets can still be placed in the `public` hierarchy. Any assets under `public`
will be served as static files by the application or web server. You should use
`app/assets` for files that must undergo some pre-processing before they are
served.
170

171 172 173
In production, Rails precompiles these files to `public/assets` by default. The
precompiled copies are then served as static assets by the web server. The files
in `app/assets` are never served directly in production.
174

175 176
### Controller Specific Assets

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
When you generate a scaffold or a controller, Rails also generates a JavaScript
file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a
Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`)
for that controller. Additionally, when generating a scaffold, Rails generates
the file scaffolds.css (or scaffolds.css.scss if `sass-rails` is in the
`Gemfile`.)

For example, if you generate a `ProjectsController`, Rails will also add a new
file at `app/assets/javascripts/projects.js.coffee` and another at
`app/assets/stylesheets/projects.css.scss`. By default these files will be ready
to use by your application immediately using the `require_tree` directive. See
[Manifest Files and Directives](#manifest-files-and-directives) for more details
on require_tree.

You can also opt to include controller specific stylesheets and JavaScript files
only in their respective controllers using the following:

`<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag
params[:controller] %>`

When doing this, ensure you are not using the `require_tree` directive, as that
will result in your assets being included more than once.

WARNING: When using asset precompilation, you will need to ensure that your
controller assets will be precompiled when loading them on a per page basis. By
default .coffee and .scss files will not be precompiled on their own. This will
result in false positives during development as these files will work just fine
since assets are compiled on the fly in development mode. When running in
production, however, you will see 500 errors since live compilation is turned
off by default. See [Precompiling Assets](#precompiling-assets) for more
information on how precompiling works.

NOTE: You must have an ExecJS supported runtime in order to use CoffeeScript.
If you are using Mac OS X or Windows, you have a JavaScript runtime installed in
your operating system. Check
[ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all
supported JavaScript runtimes.

You can also disable generation of controller specific asset files by adding the
following to your `config/application.rb` configuration:
217

V
Vijay Dev 已提交
218
```ruby
219 220 221
  config.generators do |g|
    g.assets false
  end
V
Vijay Dev 已提交
222
```
223

224 225
### Asset Organization

226 227
Pipeline assets can be placed inside an application in one of three locations:
`app/assets`, `lib/assets` or `vendor/assets`.
228

229 230
* `app/assets` is for assets that are owned by the application, such as custom
images, JavaScript files or stylesheets.
231

232 233
* `lib/assets` is for your own libraries' code that doesn't really fit into the 
scope of the application or those libraries which are shared across applications.
234

235 236
* `vendor/assets` is for assets that are owned by outside entities, such as
code for JavaScript plugins and CSS frameworks.
237

238 239 240 241 242
WARNING: If you are upgrading from Rails 3, please take into account that assets
under `lib/assets` or `vendor/assets` are available for inclusion via the
application manifests but no longer part of the precompile array. See
[Precompiling Assets](#precompiling-assets) for guidance.

243
#### Search Paths
244

245 246
When a file is referenced from a manifest or a helper, Sprockets searches the
three default asset locations for it.
247

248 249 250
The default locations are: the `images`, `javascripts` and `stylesheets`
directories under the `apps/assets` folder, but these subdirectories
are not special - any path under `assets/*` will be searched.
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

For example, these files:

```
app/assets/javascripts/home.js
lib/assets/javascripts/moovinator.js
vendor/assets/javascripts/slider.js
vendor/assets/somepackage/phonebox.js
```

would be referenced in a manifest like this:

```js
//= require home
//= require moovinator
//= require slider
//= require phonebox
```

Assets inside subdirectories can also be accessed.

```
app/assets/javascripts/sub/something.js
```

is referenced as:

```js
//= require sub/something
```

282 283
You can view the search path by inspecting
`Rails.application.config.assets.paths` in the Rails console.
284

285 286
Besides the standard `assets/*` paths, additional (fully qualified) paths can be
added to the pipeline in `config/application.rb`. For example:
287 288 289 290 291

```ruby
config.assets.paths << Rails.root.join("lib", "videoplayer", "flash")
```

292 293 294
Paths are traversed in the order they occur in the search path. By default,
this means the files in `app/assets` take precedence, and will mask
corresponding paths in `lib` and `vendor`.
295

296 297 298
It is important to note that files you want to reference outside a manifest must
be added to the precompile array or they will not be available in the production
environment.
299

300
#### Using Index Files
301

302 303
Sprockets uses files named `index` (with the relevant extensions) for a special
purpose.
304

305 306 307 308
For example, if you have a jQuery library with many modules, which is stored in
`lib/assets/library_name`, the file `lib/assets/library_name/index.js` serves as
the manifest for all files in this library. This file could include a list of
all the required files in order, or a simple `require_tree` directive.
309

310
The library as a whole can be accessed in the application manifest like so:
311 312 313 314 315

```js
//= require library_name
```

316 317
This simplifies maintenance and keeps things clean by allowing related code to
be grouped before inclusion elsewhere.
318 319 320

### Coding Links to Assets

321 322
Sprockets does not add any new methods to access your assets - you still use the
familiar `javascript_include_tag` and `stylesheet_link_tag`:
323 324

```erb
325
<%= stylesheet_link_tag "application", media: "all" %>
326 327 328
<%= javascript_include_tag "application" %>
```

329 330 331 332 333 334 335 336 337 338 339
If using the turbolinks gem, which is included by default in Rails 4, then
include the 'data-turbolinks-track' option which causes turbolinks to check if
an asset has been updated and if so loads it into the page:

```erb
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
```

In regular views you can access images in the `public/assets/images` directory
like this:
340 341 342 343 344

```erb
<%= image_tag "rails.png" %>
```

345 346 347
Provided that the pipeline is enabled within your application (and not disabled
in the current environment context), this file is served by Sprockets. If a file
exists at `public/assets/rails.png` it is served by the web server.
348

349 350 351 352
Alternatively, a request for a file with an MD5 hash such as
`public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same
way. How these hashes are generated is covered in the [In
Production](#in-production) section later on in this guide.
353

354 355 356
Sprockets will also look through the paths specified in `config.assets.paths`, 
which includes the standard application paths and any paths added by Rails 
engines.
357

358 359
Images can also be organized into subdirectories if required, and then can be
accessed by specifying the directory's name in the tag:
360 361 362 363 364

```erb
<%= image_tag "icons/rails.png" %>
```

365 366 367 368
WARNING: If you're precompiling your assets (see [In Production](#in-production)
below), linking to an asset that does not exist will raise an exception in the
calling page. This includes linking to a blank string. As such, be careful using
`image_tag` and the other helpers with user-supplied data.
369 370 371

#### CSS and ERB

372 373 374
The asset pipeline automatically evaluates ERB. This means if you add an
`erb` extension to a CSS asset (for example, `application.css.erb`), then
helpers like `asset_path` are available in your CSS rules:
375 376 377 378 379

```css
.class { background-image: url(<%= asset_path 'image.png' %>) }
```

380 381 382 383 384
This writes the path to the particular asset being referenced. In this example,
it would make sense to have an image in one of the asset load paths, such as
`app/assets/images/image.png`, which would be referenced here. If this image is
already available in `public/assets` as a fingerprinted file, then that path is
referenced.
385

386 387
If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) -
a method of embedding the image data directly into the CSS file - you can use
388
the `asset_data_uri` helper.
389 390 391 392 393 394 395 396 397 398 399

```css
#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
```

This inserts a correctly-formatted data URI into the CSS source.

Note that the closing tag cannot be of the style `-%>`.

#### CSS and Sass

400 401 402 403
When using the asset pipeline, paths to assets must be re-written and
`sass-rails` provides `-url` and `-path` helpers (hyphenated in Sass,
underscored in Ruby) for the following asset classes: image, font, video, audio,
JavaScript and stylesheet.
404 405 406 407

* `image-url("rails.png")` becomes `url(/assets/rails.png)`
* `image-path("rails.png")` becomes `"/assets/rails.png"`.

408 409
The more generic form can also be used but the asset path and class must both be
specified:
410 411 412 413 414 415

* `asset-url("rails.png", image)` becomes `url(/assets/rails.png)`
* `asset-path("rails.png", image)` becomes `"/assets/rails.png"`

#### JavaScript/CoffeeScript and ERB

416 417 418
If you add an `erb` extension to a JavaScript asset, making it something such as
`application.js.erb`, you can then use the `asset_path` helper in your
JavaScript code:
419 420

```js
421
$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });
422 423 424 425
```

This writes the path to the particular asset being referenced.

426 427
Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb`
extension (e.g., `application.js.coffee.erb`):
428 429 430 431 432 433 434

```js
$('#logo').attr src: "<%= asset_path('logo.png') %>"
```

### Manifest Files and Directives

435
Sprockets uses manifest files to determine which assets to include and serve.
436
These manifest files contain _directives_ - instructions that tell Sprockets
437 438 439 440 441 442 443
which files to require in order to build a single CSS or JavaScript file. With
these directives, Sprockets loads the files specified, processes them if
necessary, concatenates them into one single file and then compresses them (if
`Rails.application.config.assets.compress` is true). By serving one file rather
than many, the load time of pages can be greatly reduced because the browser
makes fewer requests. Compression also reduces file size, enabling the
browser to download them faster.
444

445

446 447
For example, a new Rails 4 application includes a default
`app/assets/javascripts/application.js` file containing the following lines:
448 449 450 451 452 453 454 455

```js
// ...
//= require jquery
//= require jquery_ujs
//= require_tree .
```

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
In JavaScript files, Sprockets directives begin with `//=`. In the above case,
the file is using the `require` and the `require_tree` directives. The `require`
directive is used to tell Sprockets the files you wish to require. Here, you are
requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere
in the search path for Sprockets. You need not supply the extensions explicitly.
Sprockets assumes you are requiring a `.js` file when done from within a `.js`
file.

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. You can also use the
`require_directory` directive which includes all JavaScript files only in the
directory specified, without recursion.

Directives are processed top to bottom, but the order in which files are
included by `require_tree` is unspecified. You should not rely on any particular
order among those. If you need to ensure some particular JavaScript ends up
above some other in the concatenated file, require the prerequisite file first
in the manifest. Note that the family of `require` directives prevents files
from being included twice in the output.

Rails also creates a default `app/assets/stylesheets/application.css` file
which contains these lines:
479

480
```css
481 482 483 484 485 486
/* ...
*= require_self
*= require_tree .
*/
```

487 488 489 490 491 492 493 494 495
Rails 4 creates both `app/assets/javascripts/application.js` and
`app/assets/stylesheets/application.css` regardless of whether the
--skip-sprockets option is used when creating a new rails application. This is
so you can easily add asset pipelining later if you like.

The directives that work in JavaScript files also work in stylesheets
(though obviously including stylesheets rather than JavaScript files). The
`require_tree` directive in a CSS manifest works the same way as the JavaScript
one, requiring all stylesheets from the current directory.
496

497 498 499
In this example, `require_self` is used. This puts the CSS contained within the
file (if any) at the precise location of the `require_self` call. If
`require_self` is called more than once, only the last call is respected.
500

501 502 503 504 505
NOTE. If you want to use multiple Sass files, you should generally use the [Sass
`@import`
rule](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import) instead
of these Sprockets directives. Using Sprockets directives all Sass files exist
within their own scope, making variables or mixins only available within the
506 507 508 509 510
document they were defined in. You can do file globbing as well using
`@import "*"`, and `@import "**/*"` to add the whole tree equivalent to how
`require_tree` works. Check the [sass-rails 
documentation](https://github.com/rails/sass-rails#features) for more info and
important caveats.
511

512 513 514
You can have as many manifest files as you need. For example, the `admin.css`
and `admin.js` manifest could contain the JS and CSS files that are used for the
admin section of an application.
515

516 517 518
The same remarks about ordering made above apply. In particular, you can specify
individual files and they are compiled in the order specified. For example, you
might concatenate three CSS files together this way:
519 520 521 522 523 524 525 526 527 528 529

```js
/* ...
*= require reset
*= require layout
*= require chrome
*/
```

### Preprocessing

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
The file extensions used on an asset determine what preprocessing is applied.
When a controller or a scaffold is generated with the default Rails gemset, a
CoffeeScript file and a SCSS file are generated in place of a regular JavaScript
and CSS file. The example used before was a controller called "projects", which
generated an `app/assets/javascripts/projects.js.coffee` and an
`app/assets/stylesheets/projects.css.scss` file.

In development mode, or if the asset pipeline is disabled, when these files are 
requested they are processed by the processors provided by the `coffee-script`
and `sass` gems and then sent back to the browser as JavaScript and CSS
respectively. When asset pipelining is enabled, these files are preprocessed and
placed in the `public/assets` directory for serving by either the Rails app or
web server.

Additional layers of preprocessing can be requested by adding other extensions,
where each extension is processed in a right-to-left manner. These should be
used in the order the processing should be applied. For example, a stylesheet
called `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB,
548
then SCSS, and finally served as CSS. The same applies to a JavaScript file -
549 550 551 552 553 554 555
`app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then
CoffeeScript, and served as JavaScript.

Keep in mind the order of these preprocessors is important. For example, if
you called your JavaScript file `app/assets/javascripts/projects.js.erb.coffee`
then it would be processed with the CoffeeScript interpreter first, which
wouldn't understand ERB and therefore you would run into problems.
556 557 558 559 560


In Development
--------------

561 562
In development mode, assets are served as separate files in the order they are
specified in the manifest file.
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581

This manifest `app/assets/javascripts/application.js`:

```js
//= require core
//= require projects
//= require tickets
```

would generate this HTML:

```html
<script src="/assets/core.js?body=1"></script>
<script src="/assets/projects.js?body=1"></script>
<script src="/assets/tickets.js?body=1"></script>
```

The `body` param is required by Sprockets.

582
### Turning Debugging Off
583

584 585
You can turn off debug mode by updating `config/environments/development.rb` to
include:
586 587 588 589 590

```ruby
config.assets.debug = false
```

591 592 593
When debug mode is off, Sprockets concatenates and runs the necessary
preprocessors on all files. With debug mode turned off the manifest above would
generate instead:
594 595 596 597 598

```html
<script src="/assets/application.js"></script>
```

599 600
Assets are compiled and cached on the first request after the server is started.
Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request
601
overhead on subsequent requests - on these the browser gets a 304 (Not Modified)
602
response.
603

604 605
If any of the files in the manifest have changed between requests, the server
responds with a new compiled file.
606

607
Debug mode can also be enabled in Rails helper methods:
608 609

```erb
G
Gosha Arinich 已提交
610 611
<%= stylesheet_link_tag "application", debug: true %>
<%= javascript_include_tag "application", debug: true %>
612
```
V
Vijay Dev 已提交
613

614
The `:debug` option is redundant if debug mode is already on.
615

616 617
You can also enable compression in development mode as a sanity check, and 
disable it on-demand as required for debugging.
618 619 620 621

In Production
-------------

622 623 624
In the production environment Sprockets uses the fingerprinting scheme outlined
above. By default Rails assumes assets have been precompiled and will be
served as static assets by your web server.
625

626 627 628 629
During the precompilation phase an MD5 is generated from the contents of the
compiled files, and inserted into the filenames as they are written to disc.
These fingerprinted names are used by the Rails helpers in place of the manifest
name.
630 631 632 633 634 635 636 637 638 639 640 641

For example this:

```erb
<%= javascript_include_tag "application" %>
<%= stylesheet_link_tag "application" %>
```

generates something like this:

```html
<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
642 643
<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen"
rel="stylesheet" />
644 645
```

646 647 648
Note: with the Asset Pipeline the :cache and :concat options aren't used
anymore, delete these options from the `javascript_include_tag` and
`stylesheet_link_tag`.
649

650 651 652
The fingerprinting behavior is controlled by the `config.assets.digest`
initialization option (which defaults to `true` for production and `false` for
everything else).
653

654 655 656 657
NOTE: Under normal circumstances the default `config.assets.digest` option
should not be changed. If there are no digests in the filenames, and far-future
headers are set, remote clients will never know to refetch the files when their
content changes.
658 659 660

### Precompiling Assets

661 662
Rails comes bundled with a rake task to compile the asset manifests and other
files in the pipeline.
663

664 665
Compiled assets are written to the location specified in `config.assets.prefix`.
By default, this is the `/assets` directory.
666

667 668 669
You can call this task on the server during deployment to create compiled
versions of your assets directly on the server. See the next section for
information on compiling locally.
670 671 672 673

The rake task is:

```bash
674
$ RAILS_ENV=production bundle exec rake assets:precompile
675 676
```

677 678
Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment.
Add the following line to `Capfile`:
679 680 681 682 683

```ruby
load 'deploy/assets'
```

684 685 686
This links the folder specified in `config.assets.prefix` to `shared/assets`.
If you already use this shared folder you'll need to write your own deployment
task.
687

688 689 690
It is important that this folder is shared between deployments so that remotely
cached pages referencing the old compiled assets still work for the life of
the cached page.
691

692 693
The default matcher for compiling files includes `application.js`,
`application.css` and all non-JS/CSS files (this will include all image assets
694
automatically) from `app/assets` folders including your gems:
695 696

```ruby
697
[ Proc.new { |path, fn| fn =~ /app\/assets/ && !%w(.js .css).include?(File.extname(path)) },
698
/application.(css|js)$/ ]
699 700
```

701 702 703 704
NOTE: The matcher (and other members of the precompile array; see below) is
applied to final compiled file names. This means anything that compiles to
JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and
`.scss` files are **not** automatically included as they compile to JS/CSS.
705

706 707
If you have other manifests or individual stylesheets and JavaScript files to
include, you can add them to the `precompile` array in `config/application.rb`:
708 709 710 711 712

```ruby
config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
```

713
Or, you can opt to precompile all assets with something like this:
714

V
Vijay Dev 已提交
715
```ruby
716
# config/application.rb
G
Gosha Arinich 已提交
717
config.assets.precompile << Proc.new do |path|
V
Vijay Dev 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730
  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 "including asset: " + full_path
      true
    else
      puts "excluding asset: " + full_path
      false
    end
  else
    false
  end
G
Gosha Arinich 已提交
731
end
V
Vijay Dev 已提交
732
```
733

734 735
NOTE. Always specify an expected compiled filename that ends with .js or .css,
even if you want to add Sass or CoffeeScript files to the precompile array.
736

737 738 739 740
The rake task also generates a `manifest-md5hash.json` that contains a list with
all your assets and their respective fingerprints. This is used by the Rails
helper methods to avoid handing the mapping requests back to Sprockets. A
typical manifest file looks like:
741

742 743 744 745 746 747 748 749 750 751 752
```ruby
{"files":{"application-723d1be6cc741a3aabb1cec24276d681.js":{"logical_path":"application.js","mtime":"2013-07-26T22:55:03-07:00","size":302506,
"digest":"723d1be6cc741a3aabb1cec24276d681"},"application-12b3c7dd74d2e9df37e7cbb1efa76a6d.css":{"logical_path":"application.css","mtime":"2013-07-26T22:54:54-07:00","size":1560,
"digest":"12b3c7dd74d2e9df37e7cbb1efa76a6d"},"application-1c5752789588ac18d7e1a50b1f0fd4c2.css":{"logical_path":"application.css","mtime":"2013-07-26T22:56:17-07:00","size":1591,
"digest":"1c5752789588ac18d7e1a50b1f0fd4c2"},"favicon-a9c641bf2b81f0476e876f7c5e375969.ico":{"logical_path":"favicon.ico","mtime":"2013-07-26T23:00:10-07:00","size":1406,
"digest":"a9c641bf2b81f0476e876f7c5e375969"},"my_image-231a680f23887d9dd70710ea5efd3c62.png":{"logical_path":"my_image.png","mtime":"2013-07-26T23:00:27-07:00","size":6646,
"digest":"231a680f23887d9dd70710ea5efd3c62"}},"assets"{"application.js":
"application-723d1be6cc741a3aabb1cec24276d681.js","application.css":
"application-1c5752789588ac18d7e1a50b1f0fd4c2.css",
"favicon.ico":"favicona9c641bf2b81f0476e876f7c5e375969.ico","my_image.png":
"my_image-231a680f23887d9dd70710ea5efd3c62.png"}}
753 754
```

755 756
The default location for the manifest is the root of the location specified in
`config.assets.prefix` ('/assets' by default).
757

758 759 760
NOTE: If there are missing precompiled files in production you will get an
`Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError`
exception indicating the name of the missing file(s).
761

762
#### Far-future Expires Header
763

764 765 766 767
Precompiled assets exist on the filesystem and are served directly by your web
server. They do not have far-future headers by default, so to get the benefit of
fingerprinting you'll have to update your server configuration to add those
headers.
768 769 770 771

For Apache:

```apache
772 773
# The Expires* directives requires the Apache module
# `mod_expires` to be enabled.
774
<Location /assets/>
775
  # Use of ETag is discouraged when Last-Modified is present
776
  Header unset ETag FileETag None
777
  # RFC says only cache for 1 year
778
  ExpiresActive On ExpiresDefault "access plus 1 year"
779
</Location>
780 781 782 783 784 785 786 787 788 789 790 791 792 793
```

For nginx:

```nginx
location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;

  add_header ETag "";
  break;
}
```

794
#### GZip Compression
795

796 797 798 799 800 801 802
When files are precompiled, Sprockets also creates a
[gzipped](http://en.wikipedia.org/wiki/Gzip) (.gz) version of your assets. Web
servers are typically configured to use a moderate compression ratio as a
compromise, but since precompilation happens once, Sprockets uses the maximum
compression ratio, thus reducing the size of the data transfer to the minimum.
On the other hand, web servers can be configured to serve compressed content
directly from disk, rather than deflating non-compressed files themselves.
803 804 805 806 807 808 809 810 811 812 813 814

Nginx is able to do this automatically enabling `gzip_static`:

```nginx
location ~ ^/(assets)/  {
  root /path/to/public;
  gzip_static on; # to serve pre-gzipped version
  expires max;
  add_header Cache-Control public;
}
```

815 816 817
This directive is available if the core module that provides this feature was
compiled with the web server. Ubuntu/Debian packages, even `nginx-light`, have
the module compiled. Otherwise, you may need to perform a manual compilation:
818 819 820 821 822

```bash
./configure --with-http_gzip_static_module
```

823 824
If you're compiling nginx with Phusion Passenger you'll need to pass that option
when prompted.
825

826 827
A robust configuration for Apache is possible but tricky; please Google around.
(Or help update this Guide if you have a good configuration example for Apache.)
828 829 830

### Local Precompilation

831 832
There are several reasons why you might want to precompile your assets locally.
Among them are:
833 834

* You may not have write access to your production file system.
835 836
* You may be deploying to more than one server, and want to avoid
duplication of work.
837 838
* You may be doing frequent deploys that do not include asset changes.

839 840
Local compilation allows you to commit the compiled files into source control,
and deploy as normal.
841 842 843 844 845 846 847 848 849 850 851 852

There are two caveats:

* You must not run the Capistrano deployment task that precompiles assets.
* You must change the following two application configuration settings.

In `config/environments/development.rb`, place the following line:

```ruby
config.assets.prefix = "/dev-assets"
```

853 854 855 856 857
The `prefix` change makes Sprockets use a different URL for serving assets in
development mode, and pass all requests to Sprockets. The prefix is still set to
`/assets` in the production environment. Without this change, the application
would serve the precompiled assets from `/assets` in development, and you would
not see any local changes until you compile assets again.
858

859 860
You will also need to ensure any necessary compressors or minifiers are
available on your development system.
861

862 863 864
In practice, this will allow you to precompile locally, have those files in your
working tree, and commit those files to source control when needed.  Development
mode will work as expected.
865 866 867

### Live Compilation

868 869
In some circumstances you may wish to use live compilation. In this mode all
requests for assets in the pipeline are handled by Sprockets directly.
870 871 872 873 874 875 876

To enable this option set:

```ruby
config.assets.compile = true
```

877 878 879
On the first request the assets are compiled and cached as outlined in
development above, and the manifest names used in the helpers are altered to
include the MD5 hash.
880

881 882 883 884 885
Sprockets also sets the `Cache-Control` HTTP header to `max-age=31536000`. This
signals all caches between your server and the client browser that this content
(the file served) can be cached for 1 year. The effect of this is to reduce the
number of requests for this asset from your server; the asset has a good chance
of being in the local browser cache or some intermediate cache.
886

887 888
This mode uses more memory, performs more poorly than the default and is not
recommended.
889

890 891
If you are deploying a production application to a system without any
pre-existing JavaScript runtimes, you may want to add one to your Gemfile:
892 893 894 895 896 897 898

```ruby
group :production do
  gem 'therubyracer'
end
```

899 900
### CDNs

901 902
If your assets are being served by a CDN, ensure they don't stick around in your
cache forever. This can cause problems. If you use
903 904 905
`config.action_controller.perform_caching = true`, Rack::Cache will use
`Rails.cache` to store assets. This can cause your cache to fill up quickly.

906 907 908 909
Every cache is different, so evaluate how your CDN handles caching and make sure
that it plays nicely with the pipeline. You may find quirks related to your
specific set up, you may not. The defaults nginx uses, for example, should give
you no problems when used as an HTTP cache.
910

911 912 913 914 915
Customizing the Pipeline
------------------------

### CSS Compression

916
There is currently one option for compressing CSS, YUI. The [YUI CSS
H
Hiroshige Umino 已提交
917
compressor](http://yui.github.io/yuicompressor/css.html) provides
918
minification.
919

920 921
The following line enables YUI compression, and requires the `yui-compressor`
gem.
922 923 924 925 926 927 928

```ruby
config.assets.css_compressor = :yui
```

### JavaScript Compression

929 930 931
Possible options for JavaScript compression are `:closure`, `:uglifier` and
`:yui`. These require the use of the `closure-compiler`, `uglifier` or
`yui-compressor` gems, respectively.
932

933 934 935 936 937
The default Gemfile includes [uglifier](https://github.com/lautis/uglifier).
This gem wraps [UglifyJS](https://github.com/mishoo/UglifyJS) (written for
NodeJS) in Ruby. It compresses your code by removing white space and comments,
shortening local variable names, and performing other micro-optimizations such
as changing `if` and `else` statements to ternary operators where possible.
938 939 940 941 942 943 944

The following line invokes `uglifier` for JavaScript compression.

```ruby
config.assets.js_compressor = :uglifier
```

945 946 947
NOTE: You will need an [ExecJS](https://github.com/sstephenson/execjs#readme)
supported runtime in order to use `uglifier`. If you are using Mac OS X or
Windows you have a JavaScript runtime installed in your operating system.
948

949 950 951 952 953
NOTE: The `config.assets.compress` initialization option is no longer used in
Rails 4 to enable either CSS or JavaScript compression. Setting it will have no
effect on the application. Instead, setting `config.assets.css_compressor` and
`config.assets.js_compressor` will control compression of CSS and JavaScript
assets.
954 955 956

### Using Your Own Compressor

957 958 959
The compressor config settings for CSS and JavaScript also take any object.
This object must have a `compress` method that takes a string as the sole
argument and it must return a string.
960 961 962 963 964 965 966 967 968

```ruby
class Transformer
  def compress(string)
    do_something_returning_a_string(string)
  end
end
```

G
Gosha Arinich 已提交
969
To enable this, pass a new object to the config option in `application.rb`:
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985

```ruby
config.assets.css_compressor = Transformer.new
```


### Changing the _assets_ Path

The public path that Sprockets uses by default is `/assets`.

This can be changed to something else:

```ruby
config.assets.prefix = "/some_other_path"
```

986 987 988
This is a handy option if you are updating an older project that didn't use the
asset pipeline and already uses this path or you wish to use this path for
a new resource.
989 990 991

### X-Sendfile Headers

992 993 994 995 996
The X-Sendfile header is a directive to the web server to ignore the response
from the application, and instead serve a specified file from disk. This option
is off by default, but can be enabled if your server supports it. When enabled,
this passes responsibility for serving the file to the web server, which is
faster.
997

998 999
Apache and nginx support this option, which can be enabled in
`config/environments/production.rb`:
1000 1001 1002 1003 1004 1005

```ruby
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
```

1006 1007 1008 1009
WARNING: If you are upgrading an existing application and intend to use this
option, take care to paste this configuration option only into `production.rb`
and any other environments you define with production behavior (not
`application.rb`).
1010 1011 1012 1013

Assets Cache Store
------------------

1014 1015 1016
The default Rails cache store will be used by Sprockets to cache assets in
development and production. This can be changed by setting
`config.assets.cache_store`:
1017 1018 1019 1020 1021

```ruby
config.assets.cache_store = :memory_store
```

1022 1023
The options accepted by the assets cache store are the same as the application's
cache store.
1024 1025

```ruby
1026
config.assets.cache_store = :memory_store, { size: 32.megabytes }
1027 1028 1029 1030 1031 1032 1033
```

Adding Assets to Your Gems
--------------------------

Assets can also come from external sources in the form of gems.

1034 1035 1036 1037 1038 1039
A good example of this is the `jquery-rails` gem which comes with Rails as the
standard JavaScript library gem. This gem contains an engine class which
inherits from `Rails::Engine`. By doing this, Rails is informed that the
directory for this gem may contain assets and the `app/assets`, `lib/assets` and
`vendor/assets` directories of this engine are added to the search path of
Sprockets.
1040 1041 1042 1043

Making Your Library or Gem a Pre-Processor
------------------------------------------

1044
As Sprockets uses [Tilt](https://github.com/rtomayko/tilt) as a generic
1045 1046
interface to different templating engines, your gem should just implement the
Tilt template protocol. Normally, you would subclass `Tilt::Template` and
1047 1048 1049
reimplement the `prepare` method, which initializes your template, and the
`evaluate` method, which returns the processed source. The original source is
stored in `data`. Have a look at
1050 1051 1052 1053 1054 1055
[`Tilt::Template`](https://github.com/rtomayko/tilt/blob/master/lib/tilt/template.rb)
sources to learn more.

```ruby
module BangBang
  class Template < ::Tilt::Template
1056 1057 1058 1059
    def prepare
      # Do any initialization here
    end

1060 1061
    # Adds a "!" to original template.
    def evaluate(scope, locals, &block)
1062
      "#{data}!"
1063 1064 1065 1066 1067 1068
    end
  end
end
```

Now that you have a `Template` class, it's time to associate it with an
V
Vipul A M 已提交
1069
extension for template files:
1070 1071 1072 1073

```ruby
Sprockets.register_engine '.bang', BangBang::Template
```
1074 1075 1076 1077

Upgrading from Old Versions of Rails
------------------------------------

1078 1079 1080 1081
There are a few issues when upgrading from Rails 3.0 or Rails 2.x. The first is
moving the files from `public/` to the new locations. See [Asset
Organization](#asset-organization) above for guidance on the correct locations
for different file types.
1082

1083 1084 1085
Next will be avoiding duplicate JavaScript files. Since jQuery is the default
JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js`
into `app/assets` and it will be included automatically.
1086

1087 1088
The third is updating the various environment files with the correct default
options.
1089 1090 1091 1092 1093 1094 1095

In `application.rb`:

```ruby
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'

1096
# Change the path that assets are served from config.assets.prefix = "/assets"
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
```

In `development.rb`:

```ruby
# Expands the lines which load the assets
config.assets.debug = true
```

And in `production.rb`:

```ruby
1109 1110
# Choose the compressors to use (if any) config.assets.js_compressor  =
# :uglifier config.assets.css_compressor = :yui
1111 1112 1113 1114

# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false

1115
# Generate digests for assets URLs. This is planned for deprecation.
1116 1117
config.assets.digest = true

1118 1119
# Precompile additional assets (application.js, application.css, and all
# non-JS/CSS are already added) config.assets.precompile += %w( search.js )
1120 1121
```

1122 1123 1124 1125
Rails 4 no longer sets default config values for Sprockets in `test.rb`, so
`test.rb` now requies Sprockets configuration. The old defaults in the test
environment are: `config.assets.compile = true`, `config.assets.compress =
false`, `config.assets.debug = false` and `config.assets.digest = false`.
1126 1127 1128 1129

The following should also be added to `Gemfile`:

```ruby
1130 1131 1132
gem 'sass-rails',   "~> 3.2.3"
gem 'coffee-rails', "~> 3.2.1"
gem 'uglifier'
1133
```