Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 461 lines (320 sloc) 15.698 kb
3f1ac2a Sam Stephenson Add new readme
authored
1 # Sprockets: Rack-based asset packaging
2
3 Sprockets is a Ruby library for compiling and serving web assets.
4 It features declarative dependency management for JavaScript and CSS
5 assets, as well as a powerful preprocessor pipeline that allows you to
6 write assets in languages like CoffeeScript, Sass, SCSS and LESS.
7
8 # Installation #
9
10 Install Sprockets from RubyGems:
11
12 $ gem install sprockets
13
14 Or include it in your project's `Gemfile` with Bundler:
15
16 gem 'sprockets', '~> 2.0'
17
18 # Understanding the Sprockets Environment #
19
20 You'll need an instance of the `Sprockets::Environment` class to
21 access and serve assets from your application. Under Rails 3.1 and
22 later, `YourApp::Application.assets` is a preconfigured
23 `Sprockets::Environment` instance. For Rack-based applications, create
24 an instance in `config.ru`.
25
26 The Sprockets `Environment` has methods for retrieving and serving
27 assets, manipulating the load path, and registering processors. It is
28 also a Rack application that can be mounted at a URL to serve assets
29 over HTTP.
30
31 ## The Load Path ##
32
33 The *load path* is an ordered list of directories that Sprockets uses
34 to search for assets.
35
36 In the simplest case, a Sprockets environment's load path will consist
37 of a single directory containing your application's asset source
38 files. When mounted, the environment will serve assets from this
39 directory as if they were static files in your public root.
40
41 The power of the load path is that it lets you organize your source
42 files into multiple directories -- even directories that live outside
43 your application -- and combine those directories into a single
44 virtual filesystem. That means you can easily bundle JavaScript, CSS
45 and images into a Ruby library and import them into your application.
46
47 ### Manipulating the Load Path ###
48
49 To add a directory to your environment's load path, use the
50 `append_path` and `prepend_path` methods. Directories at the beginning
51 of the load path have precedence over subsequent directories.
52
53 environment = Sprockets::Environment.new
54 environment.append_path 'app/assets/javascripts'
55 environment.append_path 'lib/assets/javascripts'
56 environment.append_path 'vendor/assets/jquery'
57
58 In general, you should append to the path by default and reserve
558ba1b Joshua Peek Fix typo
josh authored
59 prepending for cases where you need to override existing assets.
3f1ac2a Sam Stephenson Add new readme
authored
60
61 ## Accessing Assets ##
62
63 Once you've set up your environment's load path, you can mount the
64 environment as a Rack server and request assets via HTTP. You can also
65 access assets programmatically from within your application.
66
67 ### Logical Paths ###
68
69 Assets in Sprockets are always referenced by their *logical path*.
70
71 The logical path is the path of the asset source file relative to its
72 containing directory in the load path. For example, if your load path
73 contains the directory `app/assets/javascripts`:
74
75 <table>
76 <tr>
77 <th>Asset source file</th>
78 <th>Logical path</th>
79 </tr>
80 <tr>
81 <td>app/assets/javascripts/application.js</td>
82 <td>application.js</td>
83 </tr>
84 <tr>
85 <td>app/assets/javascripts/models/project.js</td>
86 <td>models/project.js</td>
87 </tr>
88 </table>
89
90 In this way, all directories in the load path are merged to create a
91 virtual filesystem whose entries are logical paths.
92
93 ### Serving Assets Over HTTP ###
94
95 When you mount an environment, all of its assets are accessible as
96 logical paths underneath the *mount point*. For example, if you mount
97 your environment at `/assets` and request the URL
98 `/assets/application.js`, Sprockets will search your load path for the
99 file named `application.js` and serve it.
100
101 Under Rails 3.1 and later, your Sprockets environment is automatically
102 mounted at `/assets`. If you are using Sprockets with a Rack
103 application, you will need to mount the environment yourself. A good
104 way to do this is with the `map` method in `config.ru`:
105
106 require 'sprockets'
107 map '/assets' do
108 environment = Sprockets::Environment.new
109 environment.append_path 'app/assets/javascripts'
110 environment.append_path 'app/assets/stylesheets'
111 run environment
112 end
169a1e8 Joshua Peek Add version history
josh authored
113
a21f564 Christoph Olszowka Extended config.ru example instructions.
colszowka authored
114 map '/' do
115 run YourRackApp
116 end
3f1ac2a Sam Stephenson Add new readme
authored
117
118 ### Accessing Assets Programmatically ###
119
120 You can use the `find_asset` method (aliased as `[]`) to retrieve an
121 asset from a Sprockets environment. Pass it a logical path and you'll
122 get a `Sprockets::BundledAsset` instance back:
123
124 environment['application.js']
125 # => #<Sprockets::BundledAsset ...>
126
127 Call `to_s` on the resulting asset to access its contents, `length` to
128 get its length in bytes, `mtime` to query its last-modified time, and
129 `pathname` to get its full path on the filesystem.
130
131 # Using Engines #
132
133 Asset source files can be written in another language, like SCSS or
134 CoffeeScript, and automatically compiled to CSS or JavaScript by
135 Sprockets. Compilers for these languages are called *engines*.
136
137 Engines are specified by additional extensions on the asset source
138 filename. For example, a CSS file written in SCSS might have the name
139 `layout.css.scss`, while a JavaScript file written in CoffeeScript
140 might have the name `dialog.js.coffee`.
141
142 ## Styling with Sass and SCSS ##
143
144 [Sass](http://sass-lang.com/) is a language that compiles to CSS and
145 adds features like nested rules, variables, mixins and selector
146 inheritance.
147
148 If the `sass` gem is available to your application, you can use Sass
149 to write CSS assets in Sprockets.
150
151 Sprockets supports both Sass syntaxes. For the original
152 whitespace-sensitive syntax, use the extension `.css.sass`. For the
153 new SCSS syntax, use the extension `.css.scss`.
154
155 ## Styling with LESS ##
156
157 [LESS](http://lesscss.org/) extends CSS with dynamic behavior such as
158 variables, mixins, operations and functions.
159
160 If the `less` gem is available to your application, you can use LESS
161 to write CSS assets in Sprockets. Note that the LESS compiler is
162 written in JavaScript, and at the time of this writing, the `less` gem
163 depends on `therubyracer` which embeds the V8 JavaScript runtime in
164 Ruby.
165
166 To write CSS assets with LESS, use the extension `.css.less`.
167
168 ## Scripting with CoffeeScript ##
169
170 [CoffeeScript](http://jashkenas.github.com/coffee-script/) is a
171 language that compiles to the "good parts" of JavaScript, featuring a
172 cleaner syntax with array comprehensions, classes, and function
173 binding.
174
175 If the `coffee-script` gem is available to your application, you can
176 use CoffeeScript to write JavaScript assets in Sprockets. Note that
177 the CoffeeScript compiler is written in JavaScript, and you will need
178 an [ExecJS](https://github.com/sstephenson/execjs)-supported runtime
179 on your system to invoke it.
180
181 To write JavaScript assets with CoffeeScript, use the extension
182 `.js.coffee`.
183
184 ## JavaScript Templating with EJS and Eco ##
185
186 Sprockets supports *JavaScript templates* for client-side rendering of
187 strings or markup. JavaScript templates have the special format
188 extension `.jst` and are compiled to JavaScript functions.
189
190 When loaded, a JavaScript template function can be accessed by its
191 logical path as a property on the global `JST` object. Invoke a
192 template function to render the template as a string. The resulting
193 string can then be inserted into the DOM.
194
7bb96b8 Sam Stephenson Add JST example
authored
195 <!-- templates/hello.jst.ejs -->
196 <div>Hello, <span><%= name %></span>!</div>
197
198 // application.js
199 //= require templates/hello
200 $("#hello").html(JST["templates/hello"]({ name: "Sam" }));
3f1ac2a Sam Stephenson Add new readme
authored
201
202 Sprockets supports two JavaScript template languages:
203 [EJS](https://github.com/sstephenson/ruby-ejs), for embedded
204 JavaScript, and [Eco](https://github.com/sstephenson/ruby-eco), for
205 embedded CoffeeScript. Both languages use the familiar `<% … %>`
206 syntax for embedding logic in templates.
207
208 If the `ejs` gem is available to your application, you can use EJS
209 templates in Sprockets. EJS templates have the extension `.jst.ejs`.
210
211 If the `eco` gem is available to your application, you can use [Eco
212 templates](https://github.com/sstephenson/eco) in Sprockets. Eco
213 templates have the extension `.jst.eco`. Note that the `eco` gem
214 depends on the CoffeeScript compiler, so the same caveats apply as
215 outlined above for the CoffeeScript engine.
216
217 ## Invoking Ruby with ERB ##
218
219 Sprockets provides an ERB engine for preprocessing assets using
220 embedded Ruby code. Append `.erb` to a CSS or JavaScript asset's
221 filename to enable the ERB engine.
222
223 **Note**: Sprockets processes multiple engine extensions in order from
224 right to left, so you can use multiple engines with a single
225 asset. For example, to have a CoffeeScript asset that is first
226 preprocessed with ERB, use the extension `.js.coffee.erb`.
227
228 Ruby code embedded in an asset is evaluated in the context of a
229 `Sprockets::Context` instance for the given asset. Common uses for ERB
230 include:
231
232 - embedding another asset as a Base64-encoded `data:` URI with the
233 `asset_data_uri` helper
234 - inserting the URL to another asset, such as with the `asset_path`
235 helper provided by the Sprockets Rails plugin
236 - embedding other application resources, such as a localized string
237 database, in a JavaScript asset via JSON
238 - embedding version constants loaded from another file
239
240 See the [Helper Methods](#FIXME) section for more information about
241 interacting with `Sprockets::Context` instances via ERB.
242
243 ### String Interpolation Syntax ###
244
245 If you need access to Ruby from an asset but cannot use ERB's `<% …
246 %>` syntax, Sprockets also supports Ruby string interpolation syntax
247 (`#{ … }`) with the `.str` engine extension.
248
249 # Managing and Bundling Dependencies #
250
251 You can create *asset bundles* -- ordered concatenations of asset
252 source files -- by specifying dependencies in a special comment syntax
253 at the top of each source file.
254
255 Sprockets reads these comments, called *directives*, and processes
256 them to recursively build a dependency graph. When you request an
257 asset with dependencies, the dependencies will be included in order at
258 the top of the file.
259
260 ## The Directive Processor ##
261
262 Sprockets runs the *directive processor* on each CSS and JavaScript
263 source file. The directive processor scans for comment lines beginning
264 with `=` in comment blocks at the top of the file.
265
266 //= require jquery
267 //= require jquery-ui
268 //= require backbone
269 //= require_tree .
270
271 The first word immediately following `=` specifies the directive
272 name. Any words following the directive name are treated as
273 arguments. Arguments may be placed in single or double quotes if they
274 contain spaces, similar to commands in the Unix shell.
275
276 **Note**: Non-directive comment lines will be preserved in the final
277 asset, but directive comments are stripped after
278 processing. Sprockets will not look for directives in comment blocks
279 that occur after the first line of code.
280
281 ### Supported Comment Types ###
282
283 The directive processor understands comment blocks in three formats:
284
285 /* Multi-line comment blocks (CSS, SCSS, JavaScript)
286 *= require foo
287 */
288
289 // Single-line comment blocks (SCSS, JavaScript)
290 //= require foo
291
292 # Single-line comment blocks (CoffeeScript)
293 #= require foo
294
295 ## Sprockets Directives ##
296
297 You can use the following directives to declare dependencies in asset
298 source files.
299
300 For directives that take a *path* argument, you may specify either a
301 logical path or a relative path. Relative paths begin with `./` and
302 reference files relative to the location of the current file.
303
304 ### The `require` Directive ###
305
306 `require` *path* inserts the contents of the asset source file
307 specified by *path*. If the file is required multiple times, it will
308 appear in the bundle only once.
309
310 ### The `include` Directive ###
311
312 `include` *path* works like `require`, but inserts the contents of the
313 specified source file even if it has already been included or
314 required.
315
316 ### The `require_directory` Directive ###
317
318 `require_directory` *path* requires all source files of the same
319 format in the directory specified by *path*. Files are required in
320 alphabetical order.
321
322 ### The `require_tree` Directive ###
323
324 `require_tree` *path* works like `require_directory`, but operates
325 recursively to require all files in all subdirectories of the
326 directory specified by *path*.
327
328 ### The `require_self` Directive ###
329
330 `require_self` tells Sprockets to insert the body of the current
331 source file before any subsequent `require` or `include` directives.
332
333 ### The `depend_on` Directive ###
334
335 `depend_on` *path* declares a dependency on the given *path* without
336 including it in the bundle. This is useful when you need to expire an
337 asset's cache in response to a change in another file.
338
d4c60a1 Elia Schito Add `stub` directive documentation in README
elia authored
339 ### The `stub` Directive ###
340
341 `stub` *path* allows dependency to be excluded from the asset bundle.
0c7eec9 Joshua Peek Add changelog for 2.3.2
josh authored
342 The *path* must be a valid asset and may or may not already be part
343 of the bundle. Once stubbed, it is blacklisted and can't be brought
d4c60a1 Elia Schito Add `stub` directive documentation in README
elia authored
344 back by any other `require`.
345
169a1e8 Joshua Peek Add version history
josh authored
346 # Development #
347
348 ## Contributing ##
3f1ac2a Sam Stephenson Add new readme
authored
349
b6624a7 Sam Stephenson Fix contributing section
authored
350 The Sprockets source code is [hosted on
351 GitHub](https://github.com/sstephenson/sprockets). You can check out a
352 copy of the latest code using Git:
3f1ac2a Sam Stephenson Add new readme
authored
353
b6624a7 Sam Stephenson Fix contributing section
authored
354 $ git clone https://github.com/sstephenson/sprockets.git
3f1ac2a Sam Stephenson Add new readme
authored
355
356 If you've found a bug or have a question, please open an issue on the
357 [Sprockets issue
358 tracker](https://github.com/sstephenson/sprockets/issues). Or, clone
359 the Sprockets repository, write a failing test case, fix the bug and
360 submit a pull request.
361
169a1e8 Joshua Peek Add version history
josh authored
362 ## Version History ##
363
6f95165 Joshua Peek Add date to 2.5.0 release
josh authored
364 **2.5.0** (September 4, 2012)
bd1be46 Joshua Peek Bake in sass compressor
josh authored
365
9d5e4db Joshua Peek Add ruby 2.0 warning fix to changelog
josh authored
366 * Fixed Ruby 2.0 RegExp warning
2ad18c4 Joshua Peek Stub out context asset url helpers
josh authored
367 * Provide stubbed implementation of context *_path helpers
bd1be46 Joshua Peek Bake in sass compressor
josh authored
368 * Add SassCompressor
369
e12bc65 Joshua Peek Add log level changes
josh authored
370 **2.4.5** (July 10, 2012)
371
372 * Tweaked some logger levels
373
92b7d12 Joshua Peek Add changelog for 2.4.4
josh authored
374 **2.4.4** (July 2, 2012)
375
376 * Canonicalize logical path extensions
377 * Check absolute paths passed to depend_on
378
8f29cfe Joshua Peek Add changelog entries for 2.4.3
josh authored
379 **2.4.3** (May 16, 2012)
380
381 * Exposed :sprockets in sass options
382 * Include dependency paths in asset mtime
383
21a16aa Joshua Peek Update changelog for 2.4.2
josh authored
384 **2.4.2** (May 7, 2012)
385
386 * Fixed MultiJson feature detect
387
42769e7 Joshua Peek Update changelog for 2.4.1
josh authored
388 **2.4.1** (April 26, 2012)
389
390 * Fixed MultiJson API change
391 * Fixed gzip mtime
392
a1546ef Joshua Peek Prepare 2.4
josh authored
393 **2.4.0** (March 27, 2012)
4fa453a Joshua Peek Add registries to changelog
josh authored
394
395 * Added global path registry
396 * Added global processor registry
397
0c7eec9 Joshua Peek Add changelog for 2.3.2
josh authored
398 **2.3.2** (March 26, 2012)
399
400 * Fix Context#logical_path with dots
401
0edbb37 Joshua Peek Changelog for 2.3.1
josh authored
402 **2.3.1** (February 11, 2012)
403
404 * Added bytesize to manifest
405 * Added Asset#bytesize alias
406 * Security: Check path for forbidden access after unescaping
407
3dac863 Kevin Moore 2.3 is released
kevmoo authored
408 **2.3.0** (January 16, 2012)
e3c40eb Joshua Peek Update 2.2 changelog
josh authored
409
b6580bc Joshua Peek Add sass note to changelog
josh authored
410 * Added special Sass importer that automatically tracks any `@import`ed files.
411
e3c40eb Joshua Peek Update 2.2 changelog
josh authored
412 **2.2.0** (January 10, 2012)
6e6dec5 Joshua Peek Add changelog note for per env encodings
josh authored
413
95333a1 Joshua Peek Add changelog entry
josh authored
414 * Added `sprockets` command line utility.
415 * Added rake/sprocketstask.
9fe8a25 Joshua Peek Add rake task to changelog
josh authored
416 * Added json manifest log of compiled assets.
417 * Added `stub` directive that allows you to exclude files from the bundle.
6e6dec5 Joshua Peek Add changelog note for per env encodings
josh authored
418 * Added per environment external encoding (Environment#default_external_encoding). Defaults to UTF-8. Fixes issues where LANG is not set correctly and Rubys default external is set to ASCII.
419
c63b046 Joshua Peek Add note to changelog about disabling If-Modified-Since
josh authored
420 **2.1.2** (November 20, 2011)
421
422 * Disabled If-Modified-Since server checks. Fixes some browser caching issues when serving the asset body only. If-None-Match caching is sufficent.
423
c00088e Joshua Peek Add 2.1.1 changelog
josh authored
424 **2.1.1** (November 18, 2011)
425
426 * Fix windows absolute path check bug.
427
169a1e8 Joshua Peek Add version history
josh authored
428 **2.1.0** (November 11, 2011)
429
1b1d6d6 Joshua Peek Tweak changelog
josh authored
430 * Directive comment lines are now turned into empty lines instead of removed. This way line numbers in
431 CoffeeScript syntax errors are correct.
f2baa65 Joshua Peek Add periods
josh authored
432 * Performance and caching bug fixes.
169a1e8 Joshua Peek Add version history
josh authored
433
434 **2.0.3** (October 17, 2011)
435
f2baa65 Joshua Peek Add periods
josh authored
436 * Detect format extensions from right to left.
437 * Make JST namespace configurable.
169a1e8 Joshua Peek Add version history
josh authored
438
439 **2.0.2** (October 4, 2011)
440
f2baa65 Joshua Peek Add periods
josh authored
441 * Fixed loading stale cache from bundler gems.
169a1e8 Joshua Peek Add version history
josh authored
442
443 **2.0.1** (September 30, 2011)
444
445 * Fixed bug with fingerprinting file names with multiple dots.
f2baa65 Joshua Peek Add periods
josh authored
446 * Decode URIs as default internal.
447 * Fix symlinked asset directories.
169a1e8 Joshua Peek Add version history
josh authored
448
449 **2.0.0** (August 29, 2011)
450
451 * Initial public release.
452
3f1ac2a Sam Stephenson Add new readme
authored
453 # License #
454
455 Copyright &copy; 2011 Sam Stephenson <<sstephenson@gmail.com>>
456
457 Copyright &copy; 2011 Joshua Peek <<josh@joshpeek.com>>
458
459 Sprockets is distributed under an MIT-style license. See LICENSE for
460 details.
Something went wrong with that request. Please try again.