asset_pipeline.md 48.8 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
X
Xavier Noria 已提交
2

S
Steve Klabnik 已提交
3 4
The Asset Pipeline
==================
5

6
This guide covers the asset pipeline.
7 8

After reading this guide, you will know:
9

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

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

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

21 22 23
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.
24
It allows assets in your application to be automatically combined with assets
L
Larry Kyrala 已提交
25 26
from other gems. For example, jquery-rails includes a copy of jquery.js
and enables AJAX features in Rails.
27

28 29 30
The asset pipeline is implemented by the
[sprockets-rails](https://github.com/rails/sprockets-rails) gem,
and is enabled by default. You can disable it while creating a new application by
31 32 33 34 35 36
passing the `--skip-sprockets` option.

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

37
Rails automatically adds the `sass-rails`, `coffee-rails` and `uglifier`
Y
Yauheni Dakuka 已提交
38
gems to your `Gemfile`, which are used by Sprockets for asset compression:
39 40

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

46
Using the `--skip-sprockets` option will prevent Rails from adding
Y
Yauheni Dakuka 已提交
47 48
them to your `Gemfile`, so if you later want to enable
the asset pipeline you will have to add those gems to your `Gemfile`. Also,
49 50 51 52
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:
53

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

58
To set asset compression methods, set the appropriate configuration options
59
in `production.rb` - `config.assets.css_compressor` for your CSS and
S
Steven Harman 已提交
60
`config.assets.js_compressor` for your JavaScript:
61

62 63
```ruby
config.assets.css_compressor = :yui
B
Brad Dunbar 已提交
64
config.assets.js_compressor = :uglifier
65
```
66

67
NOTE: The `sass-rails` gem is automatically used for CSS compression if included
Y
Yauheni Dakuka 已提交
68
in the `Gemfile` and no `config.assets.css_compressor` option is set.
69 70


71
### Main Features
72

73 74 75 76
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.
77

78 79 80
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,
Z
Zach Ahn 已提交
81 82 83
Rails inserts an SHA256 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.
84

85 86 87 88 89 90 91 92 93
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.
94 95 96

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

97 98 99 100 101
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.
102

103 104 105 106 107
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_.
108

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

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

This is the strategy adopted by the Rails asset pipeline.

118 119
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:
120 121 122 123 124 125 126

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

The query string strategy has several disadvantages:

127
1. **Not all caches will reliably cache content where the filename only differs by
R
Robin Dupret 已提交
128 129
query parameters**

130 131 132 133
    [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.
134

R
Robin Dupret 已提交
135 136
2. **The file name can change between nodes in multi-server environments.**

137 138 139 140 141
    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.

R
Robin Dupret 已提交
142 143
3. **Too much cache invalidation**

144 145 146
    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.
147

148 149
Fingerprinting fixes these problems by avoiding query strings, and by ensuring
that filenames are consistent based on their content.
150

151
Fingerprinting is enabled by default for both the development and production
152 153
environments. You can enable or disable it in your configuration through the
`config.assets.digest` option.
154 155 156

More reading:

157
* [Optimize caching](https://developers.google.com/speed/docs/insights/LeverageBrowserCaching)
158
* [Revving Filenames: don't use querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/)
159 160 161 162 163


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

164 165 166 167
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.
168

169
Assets can still be placed in the `public` hierarchy. Any assets under `public`
S
schneems 已提交
170
will be served as static files by the application or web server when
171
`config.public_file_server.enabled` is set to true. You should use `app/assets` for
172
files that must undergo some pre-processing before they are served.
173

174 175 176
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.
177

178 179
### Controller Specific Assets

180 181 182 183
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
Y
Yauheni Dakuka 已提交
184
the file `scaffolds.css` (or `scaffolds.scss` if `sass-rails` is in the
185 186 187
`Gemfile`.)

For example, if you generate a `ProjectsController`, Rails will also add a new
188 189
file at `app/assets/javascripts/projects.coffee` and another at
`app/assets/stylesheets/projects.scss`. By default these files will be ready
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
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
Y
Yauheni Dakuka 已提交
205
default `.coffee` and `.scss` files will not be precompiled on their own. See
206 207
[Precompiling Assets](#precompiling-assets) for more information on how
precompiling works.
208 209

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

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

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

222 223
### Asset Organization

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

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

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

233
* `vendor/assets` is for assets that are owned by outside entities, such as
234 235 236
code for JavaScript plugins and CSS frameworks. Keep in mind that third party
code with references to other files also processed by the asset Pipeline (images,
stylesheets, etc.), will need to be rewritten to use helpers like `asset_path`.
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
The default locations are: the `images`, `javascripts` and `stylesheets`
V
Vadim Golub 已提交
249
directories under the `app/assets` folder, but these subdirectories
250
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
Besides the standard `assets/*` paths, additional (fully qualified) paths can be
286
added to the pipeline in `config/initializers/assets.rb`. For example:
287 288

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

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
For example, if you have a jQuery library with many modules, which is stored in
306
`lib/assets/javascripts/library_name`, the file `lib/assets/javascripts/library_name/index.js` serves as
307 308
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
If using the turbolinks gem, which is included by default in Rails, then
330 331 332 333
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
334 335
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => "reload" %>
<%= javascript_include_tag "application", "data-turbolinks-track" => "reload" %>
336 337
```

338
In regular views you can access images in the `app/assets/images` directory
339
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

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

354 355
Sprockets will also look through the paths specified in `config.assets.paths`,
which includes the standard application paths and any paths added by Rails
356
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
If you want to use a [data URI](https://en.wikipedia.org/wiki/Data_URI_scheme) -
387
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
* `image-url("rails.png")` returns `url(/assets/rails.png)`
* `image-path("rails.png")` returns `"/assets/rails.png"`
407

408
The more generic form can also be used:
409

410 411
* `asset-url("rails.png")` returns `url(/assets/rails.png)`
* `asset-path("rails.png")` returns `"/assets/rails.png"`
412 413 414

#### JavaScript/CoffeeScript and ERB

415 416 417
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:
418 419

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

This writes the path to the particular asset being referenced.

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

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

### Manifest Files and Directives

434
Sprockets uses manifest files to determine which assets to include and serve.
435
These manifest files contain _directives_ - instructions that tell Sprockets
436 437
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
438 439 440 441 442
necessary, concatenates them into one single file and then compresses them
(based on value of `Rails.application.config.assets.js_compressor`). 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.
443

444

445
For example, a new Rails application includes a default
446
`app/assets/javascripts/application.js` file containing the following lines:
447 448 449

```js
// ...
450 451
//= require rails-ujs
//= require turbolinks
452 453 454
//= require_tree .
```

455 456 457
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
458
requiring the files `rails-ujs.js` and `turbolinks.js` that are available somewhere
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
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:
478

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

486
Rails creates both `app/assets/javascripts/application.js` and
487
`app/assets/stylesheets/application.css` regardless of whether the
S
schneems 已提交
488
--skip-sprockets option is used when creating a new Rails application. This is
489 490 491 492 493 494
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.
495

496
In this example, `require_self` is used. This puts the CSS contained within the
497
file (if any) at the precise location of the `require_self` call.
498

499
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)
K
Kevin Musiorski 已提交
500
instead of these Sprockets directives. When using Sprockets directives, Sass files exist within
501
their own scope, making variables or mixins only available within the document they were defined in.
K
Kevin Musiorski 已提交
502 503

You can do file globbing as well using `@import "*"`, and `@import "**/*"` to add the whole tree which is equivalent to how `require_tree` works. Check the [sass-rails documentation](https://github.com/rails/sass-rails#features) for more info and important caveats.
504

505 506 507
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.
508

509 510 511
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:
512 513 514 515 516 517 518 519 520 521 522

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

### Preprocessing

523 524 525 526
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
527 528
generated an `app/assets/javascripts/projects.coffee` and an
`app/assets/stylesheets/projects.scss` file.
529

530
In development mode, or if the asset pipeline is disabled, when these files are
531 532 533 534 535 536 537 538 539
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
540
called `app/assets/stylesheets/projects.scss.erb` is first processed as ERB,
541
then SCSS, and finally served as CSS. The same applies to a JavaScript file -
542
`app/assets/javascripts/projects.coffee.erb` is processed as ERB, then
543 544 545
CoffeeScript, and served as JavaScript.

Keep in mind the order of these preprocessors is important. For example, if
546
you called your JavaScript file `app/assets/javascripts/projects.erb.coffee`
547 548
then it would be processed with the CoffeeScript interpreter first, which
wouldn't understand ERB and therefore you would run into problems.
549 550 551 552 553


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

554 555
In development mode, assets are served as separate files in the order they are
specified in the manifest file.
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574

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.

575 576
### Raise an Error When an Asset is Not Found

577
If you are using sprockets-rails >= 3.2.0 you can configure what happens
578 579 580 581 582 583 584 585
when an asset lookup is performed and nothing is found. If you turn off "asset fallback"
then an error will be raised when an asset cannot be found.

```ruby
config.assets.unknown_asset_fallback = false
```

If "asset fallback" is enabled then when an asset cannot be found the path will be
S
schneems 已提交
586
output instead and no error raised. The asset fallback behavior is enabled by default.
587

588 589 590 591 592 593
### Turning Digests Off

You can turn off digests by updating `config/environments/development.rb` to
include:

```ruby
594
config.assets.digest = false
595 596 597
```

When this option is true, digests will be generated for asset URLs.
598

599
### Turning Debugging Off
600

601 602
You can turn off debug mode by updating `config/environments/development.rb` to
include:
603 604 605 606 607

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

608 609 610
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:
611 612 613 614 615

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

616 617
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
618
overhead on subsequent requests - on these the browser gets a 304 (Not Modified)
619
response.
620

621 622
If any of the files in the manifest have changed between requests, the server
responds with a new compiled file.
623

624
Debug mode can also be enabled in Rails helper methods:
625 626

```erb
G
Gosha Arinich 已提交
627 628
<%= stylesheet_link_tag "application", debug: true %>
<%= javascript_include_tag "application", debug: true %>
629
```
V
Vijay Dev 已提交
630

631
The `:debug` option is redundant if debug mode is already on.
632

633
You can also enable compression in development mode as a sanity check, and
634
disable it on-demand as required for debugging.
635 636 637 638

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

639 640 641
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.
642

Z
Zach Ahn 已提交
643
During the precompilation phase an SHA256 is generated from the contents of the
H
Hank Beaver 已提交
644
compiled files, and inserted into the filenames as they are written to disk.
645 646
These fingerprinted names are used by the Rails helpers in place of the manifest
name.
647 648 649 650 651 652 653 654 655 656 657 658

For example this:

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

generates something like this:

```html
<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
659 660
<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen"
rel="stylesheet" />
661 662
```

M
Markov Alexey 已提交
663
NOTE: with the Asset Pipeline the `:cache` and `:concat` options aren't used
664 665
anymore, delete these options from the `javascript_include_tag` and
`stylesheet_link_tag`.
666

667
The fingerprinting behavior is controlled by the `config.assets.digest`
668
initialization option (which defaults to `true`).
669

670 671 672 673
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.
674 675 676

### Precompiling Assets

677
Rails comes bundled with a task to compile the asset manifests and other
678
files in the pipeline.
679

680 681
Compiled assets are written to the location specified in `config.assets.prefix`.
By default, this is the `/assets` directory.
682

683 684 685
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.
686

687
The task is:
688 689

```bash
690
$ RAILS_ENV=production bin/rails assets:precompile
691 692
```

693 694
Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment.
Add the following line to `Capfile`:
695 696 697 698 699

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

700 701 702
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.
703

704 705 706
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.
707

708 709
The default matcher for compiling files includes `application.js`,
`application.css` and all non-JS/CSS files (this will include all image assets
710
automatically) from `app/assets` folders including your gems:
711 712

```ruby
713
[ Proc.new { |filename, path| path =~ /app\/assets/ && !%w(.js .css).include?(File.extname(filename)) },
714
/application.(css|js)$/ ]
715 716
```

717 718 719 720
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.
721

722
If you have other manifests or individual stylesheets and JavaScript files to
723
include, you can add them to the `precompile` array in `config/initializers/assets.rb`:
724 725

```ruby
S
schneems 已提交
726
Rails.application.config.assets.precompile += %w( admin.js admin.css )
727 728
```

Y
Yauheni Dakuka 已提交
729
NOTE. Always specify an expected compiled filename that ends with `.js` or `.css`,
730
even if you want to add Sass or CoffeeScript files to the precompile array.
731

Z
Zach Ahn 已提交
732
The task also generates a `.sprockets-manifest-md5hash.json` (where `md5hash` is
733
an MD5 hash) that contains a list with all your assets and their respective
Z
Zach Ahn 已提交
734 735
fingerprints. This is used by the Rails helper methods to avoid handing the
mapping requests back to Sprockets. A typical manifest file looks like:
736

737
```ruby
Z
Zach Ahn 已提交
738 739 740 741 742 743 744 745 746 747 748 749
{"files":{"application-aee4be71f1288037ae78b997df388332edfd246471b533dcedaa8f9fe156442b.js":{"logical_path":"application.js","mtime":"2016-12-23T20:12:03-05:00","size":412383,
"digest":"aee4be71f1288037ae78b997df388332edfd246471b533dcedaa8f9fe156442b","integrity":"sha256-ruS+cfEogDeueLmX3ziDMu39JGRxtTPc7aqPn+FWRCs="},
"application-86a292b5070793c37e2c0e5f39f73bb387644eaeada7f96e6fc040a028b16c18.css":{"logical_path":"application.css","mtime":"2016-12-23T19:12:20-05:00","size":2994,
"digest":"86a292b5070793c37e2c0e5f39f73bb387644eaeada7f96e6fc040a028b16c18","integrity":"sha256-hqKStQcHk8N+LA5fOfc7s4dkTq6tp/lub8BAoCixbBg="},
"favicon-8d2387b8d4d32cecd93fa3900df0e9ff89d01aacd84f50e780c17c9f6b3d0eda.ico":{"logical_path":"favicon.ico","mtime":"2016-12-23T20:11:00-05:00","size":8629,
"digest":"8d2387b8d4d32cecd93fa3900df0e9ff89d01aacd84f50e780c17c9f6b3d0eda","integrity":"sha256-jSOHuNTTLOzZP6OQDfDp/4nQGqzYT1DngMF8n2s9Dto="},
"my_image-f4028156fd7eca03584d5f2fc0470df1e0dbc7369eaae638b2ff033f988ec493.png":{"logical_path":"my_image.png","mtime":"2016-12-23T20:10:54-05:00","size":23414,
"digest":"f4028156fd7eca03584d5f2fc0470df1e0dbc7369eaae638b2ff033f988ec493","integrity":"sha256-9AKBVv1+ygNYTV8vwEcN8eDbxzaequY4sv8DP5iOxJM="}},
"assets":{"application.js":"application-aee4be71f1288037ae78b997df388332edfd246471b533dcedaa8f9fe156442b.js",
"application.css":"application-86a292b5070793c37e2c0e5f39f73bb387644eaeada7f96e6fc040a028b16c18.css",
"favicon.ico":"favicon-8d2387b8d4d32cecd93fa3900df0e9ff89d01aacd84f50e780c17c9f6b3d0eda.ico",
"my_image.png":"my_image-f4028156fd7eca03584d5f2fc0470df1e0dbc7369eaae638b2ff033f988ec493.png"}}
750 751
```

752 753
The default location for the manifest is the root of the location specified in
`config.assets.prefix` ('/assets' by default).
754

755 756 757
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).
758

759
#### Far-future Expires Header
760

S
Steven Harman 已提交
761
Precompiled assets exist on the file system and are served directly by your web
762 763 764
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.
765 766 767 768

For Apache:

```apache
769 770
# The Expires* directives requires the Apache module
# `mod_expires` to be enabled.
771
<Location /assets/>
772
  # Use of ETag is discouraged when Last-Modified is present
773
  Header unset ETag
J
Jason Nochlin 已提交
774
  FileETag None
775
  # RFC says only cache for 1 year
776
  ExpiresActive On
J
Jason Nochlin 已提交
777
  ExpiresDefault "access plus 1 year"
778
</Location>
779 780
```

A
Akshay Vishnoi 已提交
781
For NGINX:
782 783 784 785 786 787 788 789 790 791 792 793

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

  add_header ETag "";
}
```

### Local Precompilation

794 795 796 797
Sometimes, you may not want or be able to compile assets on the production
server. For instance, you may have limited write access to your production
filesystem, or you may plan to deploy frequently without making any changes to
your assets.
798

799 800 801 802
In such cases, you can precompile assets _locally_ — that is, add a finalized
set of compiled, production-ready assets to your source code repository before
pushing to production. This way, they do not need to be precompiled separately
on the production server upon each deployment.
803

804
As above, you can perform this step using
805

806 807 808
```bash
$ RAILS_ENV=production rails assets:precompile
```
809

810
Note the following caveats:
811

812 813 814
* If precompiled assets are available, they will be served — even if they no
  longer match the original (uncompiled) assets, _even on the development
  server._
815

816 817 818 819 820 821
  To ensure that the development server always compiles assets on-the-fly (and
  thus always reflects the most recent state of the code), the development
  environment _must be configured to keep precompiled assets in a different
  location than production does._ Otherwise, any assets precompiled for use in
  production will clobber requests for them in development (_i.e.,_ subsequent
  changes you make to assets will not be reflected in the browser).
822

823 824
  You can do this by adding the following line to
  `config/environments/development.rb`:
825

826 827 828 829 830 831
  ```ruby
  config.assets.prefix = "/dev-assets"
  ```
* Do not run the Capistrano deployment task that precompiles assets.
* Any necessary compressors or minifiers must be available on your development
  system.
832 833 834

### Live Compilation

835 836
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.
837 838 839 840 841 842 843

To enable this option set:

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

844 845 846
On the first request the assets are compiled and cached as outlined in [Assets
Cache Store](#assets-cache-store), and the manifest names used in the helpers
are altered to include the SHA256 hash.
847

848 849 850 851 852
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.
853

854 855
This mode uses more memory, performs more poorly than the default and is not
recommended.
856

857
If you are deploying a production application to a system without any
Y
Yauheni Dakuka 已提交
858
pre-existing JavaScript runtimes, you may want to add one to your `Gemfile`:
859 860 861

```ruby
group :production do
S
Sam 已提交
862
  gem 'mini_racer'
863 864 865
end
```

866 867
### CDNs

S
schneems 已提交
868
CDN stands for [Content Delivery
869
Network](https://en.wikipedia.org/wiki/Content_delivery_network), they are
S
schneems 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
primarily designed to cache assets all over the world so that when a browser
requests the asset, a cached copy will be geographically close to that browser.
If you are serving assets directly from your Rails server in production, the
best practice is to use a CDN in front of your application.

A common pattern for using a CDN is to set your production application as the
"origin" server. This means when a browser requests an asset from the CDN and
there is a cache miss, it will grab the file from your server on the fly and
then cache it. For example if you are running a Rails application on
`example.com` and have a CDN configured at `mycdnsubdomain.fictional-cdn.com`,
then when a request is made to `mycdnsubdomain.fictional-
cdn.com/assets/smile.png`, the CDN will query your server once at
`example.com/assets/smile.png` and cache the request. The next request to the
CDN that comes in to the same URL will hit the cached copy. When the CDN can
serve an asset directly the request never touches your Rails server. Since the
assets from a CDN are geographically closer to the browser, the request is
faster, and since your server doesn't need to spend time serving assets, it can
focus on serving application code as fast as possible.

889 890 891
#### Set up a CDN to Serve Static Assets

To set up your CDN you have to have your application running in production on
A
Anton Davydov 已提交
892
the internet at a publicly available URL, for example `example.com`. Next
893 894 895 896 897 898 899 900 901 902 903 904
you'll need to sign up for a CDN service from a cloud hosting provider. When you
do this you need to configure the "origin" of the CDN to point back at your
website `example.com`, check your provider for documentation on configuring the
origin server.

The CDN you provisioned should give you a custom subdomain for your application
such as `mycdnsubdomain.fictional-cdn.com` (note fictional-cdn.com is not a
valid CDN provider at the time of this writing). Now that you have configured
your CDN server, you need to tell browsers to use your CDN to grab assets
instead of your Rails server directly. You can do this by configuring Rails to
set your CDN as the asset host instead of using a relative path. To set your
asset host in Rails, you need to set `config.action_controller.asset_host` in
905
`config/environments/production.rb`:
906 907

```ruby
908 909 910
config.action_controller.asset_host = 'mycdnsubdomain.fictional-cdn.com'
```

S
schneems 已提交
911
NOTE: You only need to provide the "host", this is the subdomain and root
912 913 914 915 916
domain, you do not need to specify a protocol or "scheme" such as `http://` or
`https://`. When a web page is requested, the protocol in the link to your asset
that is generated will match how the webpage is accessed by default.

You can also set this value through an [environment
917
variable](https://en.wikipedia.org/wiki/Environment_variable) to make running a
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
staging copy of your site easier:

```
config.action_controller.asset_host = ENV['CDN_HOST']
```



Note: You would need to set `CDN_HOST` on your server to `mycdnsubdomain
.fictional-cdn.com` for this to work.

Once you have configured your server and your CDN when you serve a webpage that
has an asset:

```erb
<%= asset_path('smile.png') %>
```

Instead of returning a path such as `/assets/smile.png` (digests are left out
for readability). The URL generated will have the full path to your CDN.

```
http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
```

If the CDN has a copy of `smile.png` it will serve it to the browser and your
server doesn't even know it was requested. If the CDN does not have a copy it
J
James 已提交
945
will try to find it at the "origin" `example.com/assets/smile.png` and then store
946 947 948 949 950 951 952 953
it for future use.

If you want to serve only some assets from your CDN, you can use custom `:host`
option your asset helper, which overwrites value set in
`config.action_controller.asset_host`.

```erb
<%= asset_path 'image.png', host: 'mycdnsubdomain.fictional-cdn.com' %>
954 955
```

S
schneems 已提交
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
#### Customize CDN Caching Behavior

A CDN works by caching content. If the CDN has stale or bad content, then it is
hurting rather than helping your application. The purpose of this section is to
describe general caching behavior of most CDNs, your specific provider may
behave slightly differently.

##### CDN Request Caching

While a CDN is described as being good for caching assets, in reality caches the
entire request. This includes the body of the asset as well as any headers. The
most important one being `Cache-Control` which tells the CDN (and web browsers)
how to cache contents. This means that if someone requests an asset that does
not exist `/assets/i-dont-exist.png` and your Rails application returns a 404,
then your CDN will likely cache the 404 page if a valid `Cache-Control` header
is present.

S
schneems 已提交
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
##### CDN Header Debugging

One way to check the headers are cached properly in your CDN is by using [curl](
http://explainshell.com/explain?cmd=curl+-I+http%3A%2F%2Fwww.example.com). You
can request the headers from both your server and your CDN to verify they are
the same:

```
$ curl -I http://www.example/assets/application-
d0e099e021c95eb0de3615fd1d8c4d83.css
HTTP/1.1 200 OK
Server: Cowboy
Date: Sun, 24 Aug 2014 20:27:50 GMT
Connection: keep-alive
Last-Modified: Thu, 08 May 2014 01:24:14 GMT
Content-Type: text/css
Cache-Control: public, max-age=2592000
Content-Length: 126560
Via: 1.1 vegur
```

Versus the CDN copy.

```
$ curl -I http://mycdnsubdomain.fictional-cdn.com/application-
d0e099e021c95eb0de3615fd1d8c4d83.css
HTTP/1.1 200 OK Server: Cowboy Last-
Modified: Thu, 08 May 2014 01:24:14 GMT Content-Type: text/css
Cache-Control:
public, max-age=2592000
Via: 1.1 vegur
Content-Length: 126560
Accept-Ranges:
bytes
Date: Sun, 24 Aug 2014 20:28:45 GMT
Via: 1.1 varnish
Age: 885814
Connection: keep-alive
X-Served-By: cache-dfw1828-DFW
X-Cache: HIT
X-Cache-Hits:
68
X-Timer: S1408912125.211638212,VS0,VE0
```

Check your CDN documentation for any additional information they may provide
S
schneems 已提交
1019
such as `X-Cache` or for any additional headers they may add.
S
schneems 已提交
1020

1021 1022 1023 1024 1025 1026 1027
##### CDNs and the Cache-Control Header

The [cache control
header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) is a W3C
specification that describes how a request can be cached. When no CDN is used, a
browser will use this information to cache contents. This is very helpful for
assets that are not modified so that a browser does not need to re-download a
1028
website's CSS or JavaScript on every request. Generally we want our Rails server
1029 1030 1031 1032
to tell our CDN (and browser) that the asset is "public", that means any cache
can store the request. Also we commonly want to set `max-age` which is how long
the cache will store the object before invalidating the cache. The `max-age`
value is set to seconds with a maximum possible value of `31536000` which is one
S
schneems 已提交
1033
year. You can do this in your Rails application by setting
1034 1035

```
1036 1037 1038
config.public_file_server.headers = {
  'Cache-Control' => 'public, max-age=31536000'
}
1039 1040 1041 1042 1043 1044 1045 1046
```

Now when your application serves an asset in production, the CDN will store the
asset for up to a year. Since most CDNs also cache headers of the request, this
`Cache-Control` will be passed along to all future browsers seeking this asset,
the browser then knows that it can store this asset for a very long time before
needing to re-request it.

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
##### CDNs and URL based Cache Invalidation

Most CDNs will cache contents of an asset based on the complete URL. This means
that a request to

```
http://mycdnsubdomain.fictional-cdn.com/assets/smile-123.png
```

Will be a completely different cache from

```
http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
```

S
schneems 已提交
1062 1063
If you want to set far future `max-age` in your `Cache-Control` (and you do),
then make sure when you change your assets that your cache is invalidated. For
1064
example when changing the smiley face in an image from yellow to blue, you want
S
schneems 已提交
1065
all visitors of your site to get the new blue face. When using a CDN with the
1066 1067 1068 1069 1070
Rails asset pipeline `config.assets.digest` is set to true by default so that
each asset will have a different file name when it is changed. This way you
don't have to ever manually invalidate any items in your cache. By using a
different unique asset name instead, your users get the latest asset.

1071 1072 1073 1074 1075
Customizing the Pipeline
------------------------

### CSS Compression

1076
One of the options for compressing CSS is YUI. The [YUI CSS
1077
compressor](https://yui.github.io/yuicompressor/css.html) provides
1078
minification.
1079

1080 1081
The following line enables YUI compression, and requires the `yui-compressor`
gem.
1082 1083 1084 1085

```ruby
config.assets.css_compressor = :yui
```
1086
The other option for compressing CSS if you have the sass-rails gem installed is
1087 1088 1089 1090

```ruby
config.assets.css_compressor = :sass
```
1091 1092 1093

### JavaScript Compression

1094 1095 1096
Possible options for JavaScript compression are `:closure`, `:uglifier` and
`:yui`. These require the use of the `closure-compiler`, `uglifier` or
`yui-compressor` gems, respectively.
1097

Y
Yauheni Dakuka 已提交
1098
The default `Gemfile` includes [uglifier](https://github.com/lautis/uglifier).
1099 1100 1101 1102
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.
1103 1104 1105 1106 1107 1108 1109

The following line invokes `uglifier` for JavaScript compression.

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

1110
NOTE: You will need an [ExecJS](https://github.com/rails/execjs#readme)
1111
supported runtime in order to use `uglifier`. If you are using macOS or
1112
Windows you have a JavaScript runtime installed in your operating system.
1113 1114


1115 1116 1117

### Serving GZipped version of assets

S
schneems 已提交
1118 1119 1120
By default, gzipped version of compiled assets will be generated, along with
the non-gzipped version of assets. Gzipped assets help reduce the transmission
of data over the wire. You can configure this by setting the `gzip` flag.
1121 1122 1123 1124 1125

```ruby
config.assets.gzip = false # disable gzipped assets generation
```

1126 1127
### Using Your Own Compressor

1128 1129 1130
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.
1131 1132 1133 1134 1135 1136 1137 1138 1139

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

G
Gosha Arinich 已提交
1140
To enable this, pass a new object to the config option in `application.rb`:
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

```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"
```

1157 1158 1159
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.
1160 1161 1162

### X-Sendfile Headers

1163 1164 1165 1166
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
1167
faster. Have a look at [send_file](http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file)
1168
on how to use this feature.
1169

A
Akshay Vishnoi 已提交
1170
Apache and NGINX support this option, which can be enabled in
1171
`config/environments/production.rb`:
1172 1173

```ruby
A
Akshay Vishnoi 已提交
1174 1175
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
1176 1177
```

1178 1179 1180 1181
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`).
1182

1183 1184
TIP: For further details have a look at the docs of your production web server:
- [Apache](https://tn123.org/mod_xsendfile/)
A
Akshay Vishnoi 已提交
1185
- [NGINX](http://wiki.nginx.org/XSendfile)
1186

1187 1188 1189
Assets Cache Store
------------------

1190 1191
By default, Sprockets caches assets in `tmp/cache/assets` in development
and production environments. This can be changed as follows:
1192 1193

```ruby
1194 1195 1196 1197
config.assets.configure do |env|
  env.cache = ActiveSupport::Cache.lookup_store(:memory_store,
                                                { size: 32.megabytes })
end
1198 1199
```

1200 1201 1202 1203 1204 1205 1206 1207
To disable the assets cache store:

```ruby
config.assets.configure do |env|
  env.cache = ActiveSupport::Cache.lookup_store(:null_store)
end
```

1208 1209 1210 1211 1212
Adding Assets to Your Gems
--------------------------

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

1213 1214 1215 1216 1217 1218
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.
1219 1220 1221 1222

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

T
Tom Prats 已提交
1223 1224 1225 1226
Sprockets uses Processors, Transformers, Compressors, and Exporters to extend
Sprockets functionality. Have a look at
[Extending Sprockets](https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md)
to learn more. Here we registered a preprocessor to add a comment to the end
Y
Yauheni Dakuka 已提交
1227
of text/css (`.css`) files.
1228 1229

```ruby
T
Tom Prats 已提交
1230 1231 1232
module AddComment
  def self.call(input)
    { data: input[:data] + "/* Hello From my sprockets extension */" }
1233 1234 1235 1236
  end
end
```

T
Tom Prats 已提交
1237 1238
Now that you have a module that modifies the input data, it's time to register
it as a preprocessor for your mime type.
1239 1240

```ruby
T
Tom Prats 已提交
1241
Sprockets.register_preprocessor 'text/css', AddComment
1242
```
1243 1244 1245 1246

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

1247 1248 1249 1250
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.
1251

1252 1253 1254
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.
1255

1256 1257
The third is updating the various environment files with the correct default
options.
1258 1259 1260 1261 1262 1263 1264

In `application.rb`:

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

1265
# Change the path that assets are served from config.assets.prefix = "/assets"
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
```

In `development.rb`:

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

And in `production.rb`:

```ruby
A
Alexander 已提交
1278 1279 1280
# Choose the compressors to use (if any)
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :yui
1281 1282 1283 1284

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

1285
# Generate digests for assets URLs.
1286 1287
config.assets.digest = true

1288
# Precompile additional assets (application.js, application.css, and all
A
Alexander 已提交
1289
# non-JS/CSS are already added)
S
schneems 已提交
1290
# config.assets.precompile += %w( admin.js admin.css )
1291 1292
```

1293
Rails 4 and above no longer set default config values for Sprockets in `test.rb`, so
V
Vipul A M 已提交
1294
`test.rb` now requires Sprockets configuration. The old defaults in the test
1295 1296
environment are: `config.assets.compile = true`, `config.assets.compress = false`,
`config.assets.debug = false` and `config.assets.digest = false`.
1297

D
Djoume Salvetti 已提交
1298
The following should also be added to your `Gemfile`:
1299 1300

```ruby
1301 1302 1303
gem 'sass-rails',   "~> 3.2.3"
gem 'coffee-rails', "~> 3.2.1"
gem 'uglifier'
1304
```