Sprockets: Rack-based asset packaging



Install Sprockets from RubyGems:

$ gem install sprockets

Or include it in your project's Gemfile with Bundler:

gem 'sprockets', '~> 3.0'

Using Sprockets


If you are a framework developer that is using Sprockets, see Building an Asset Processing Framework.

If you are a library developer who is extending the functionality of Sprockets, see Extending Sprockets.

Below is a disjointed mix of documentation for all three of these roles. Eventually they will be moved to an appropriate guide, but for now, the recommended way to consume this documentation is to view the appropriate guide first and then supplement with docs from the README.


Index files are proxies for folders

In Sprockets, index files such as index.js or index.css inside of a folder will generate a file with the folder's name. So if you have a file named foo/index.js, it will compile down to foo.js. This is similar to Node.js's behavior of using folders as modules. It is also somewhat similar to the way that a file in public/my_folder/index.html can be reached by a request to /my_folder. This means that you cannot directly use an index file. For example this would not work:

<%= asset_path("foo/index.js") %>

Instead you would need to use:

<%= asset_path("foo.js") %>

Why would you want to use this behavior? It is common behavior where you might want to include an entire directory of files in a top level javascript. You can do this in Sprockets using require_tree .

//= require_tree .

This has the problem that files are required alphabetically. If your directory has jquery-ui.js and jquery.min.js, then Sprockets will require jquery-ui.js before jquery is required, which won't work (because jquery-ui depends on jquery). Previously the only way to get the correct ordering would be to rename your files, something like 0-jquery-ui.js. Instead of doing that you can use an index file.

For example, if you have an application.js and want all the files in the foo/ folder you could do this:

//= require foo.js

Then create a file foo/index.js that requires all the files in that folder in any order you want:

//= require ./foo.min.js
//= require ./foo-ui.js

Now, your application.js will correctly load the foo.min.js before foo-ui.js. If you used require_tree it would not work correctly.

Understanding the Sprockets Environment

You'll need an instance of the Sprockets::Environment class to access and serve assets from your application. Under Rails 4.0 and later, YourApp::Application.assets is a preconfigured Sprockets::Environment instance. For Rack-based applications, create an instance in config.ru.


The Load Path




Manipulating the Load Path


environment = Sprockets::Environment.new
environment.append_path 'app/assets/javascripts'
environment.append_path 'lib/assets/javascripts'
environment.append_path 'vendor/assets/bower_components'


Accessing Assets


Logical Paths

Assets in Sprockets are always referenced by their logical path.


Asset source file Logical path
app/assets/javascripts/application.js application.js
app/assets/javascripts/models/project.js models/project.js


Serving Assets Over HTTP



require 'sprockets'
map '/assets' do
  environment = Sprockets::Environment.new
  environment.append_path 'app/assets/javascripts'
  environment.append_path 'app/assets/stylesheets'
  run environment

map '/' do
  run YourRackApp

Accessing Assets Programmatically


# => #<Sprockets::Asset ...>

Call to_s on the resulting asset to access its contents, length to get its length in bytes, mtime to query its last-modified time, and filename to get its full path on the filesystem.

Using Processors

Asset source files can be written in another format, like SCSS or CoffeeScript, and automatically compiled to CSS or JavaScript by Sprockets. Processors that convert a file from one format to another are called transformers.

Minifying Assets

Several JavaScript and CSS minifiers are available through shorthand.

environment.js_compressor  = :uglify
environment.css_compressor = :scss

If you are using Sprockets directly with a Rack app, don't forget to add the uglifier and sass gems to your Gemfile when using above options.

Styling with Sass and SCSS



Sprockets supports both Sass syntaxes. For the original whitespace-sensitive syntax, use the extension .sass. For the new SCSS syntax, use the extension .scss.

Scripting with CoffeeScript



To write JavaScript assets with CoffeeScript, use the extension .coffee.

JavaScript Templating with EJS and Eco



<!-- templates/hello.jst.ejs -->

// application.js
//= require templates/hello



If the eco gem is available to your application, you can use Eco templates in Sprockets. Eco templates have the extension .jst.eco. Note that the eco gem depends on the CoffeeScript compiler, so the same caveats apply as outlined above for the CoffeeScript engine.

Invoking Ruby with ERB



  • embedding version constants loaded from another file


Managing and Bundling Dependencies



The Directive Processor


//= require jquery
//= require jquery-ui
//= require backbone
//= require_tree .



Supported Comment Types

The directive processor understands comment blocks in three formats:

 *= require foo
// Single-line comment blocks (SCSS, JavaScript)
//= require foo
# Single-line comment blocks (CoffeeScript)
#= require foo

Sprockets Directives



The require Directive

require path inserts the contents of the asset source file specified by path. If the same file is required multiple times with different path expressions, it will appear in the bundle only once.

The require_directory Directive


The require_tree Directive


The require_self Directive

require_self tells Sprockets to insert the body of the current source file before any subsequent require directives.

link path declares a dependency on the target path and adds it to a list of subdependencies to automatically be compiled when the asset is written out to disk.

For an example, in a CSS file you might reference an external image that always needs to be compiled along with the css file.

/*= link "logo.png" */
.logo {
  background-image: url(logo.png)

However, if you use a asset-path or asset-url SCSS helper, these links will automatically be defined for you.

.logo {
  background-image: asset-url("logo.png")

link_directory path links all the files inside the directory specified by the path

link_tree path works like link_directory, but operates recursively to link all files in all subdirectories of the directory specified by path.

The depend_on Directive


The depend_on_asset Directive

depend_on_asset path works like depend_on, but operates recursively reading the file and following the directives found. This is automatically implied if you use link, so consider if it just makes sense using link instead of depend_on_asset.

The stub Directive

stub path excludes that asset and its dependencies from the asset bundle. The path must be a valid asset and may or may not already be part of the bundle. stub should only be used at the top level bundle, not within any subdependencies.

Processor Interface

Sprockets 2.x was originally designed around Tilt's engine interface. However, starting with 3.x, a new interface has been introduced deprecating Tilt.

Similar to Rack, a processor is any "callable" (an object that responds to call). This may be a simple Proc or a full class that defines a def self.call(input) method. The call method accepts an input Hash and returns a Hash of metadata.

Also see Sprockets::ProcessorUtils for public helper methods.

Input Hash

The input Hash defines the following public fields.

  • :data - String asset contents.
  • :environment - Current Sprockets::Environment instance.
  • :cache - A Sprockets::Cache instance. See Sprockets::Cache#fetch.
  • :uri - String Asset URI.
  • :load_path - String current load path for filename.
  • :name - String logical path for filename.
  • :content_type - String content type of the output asset.
  • :metadata - Hash of processor metadata.
def self.call(input)
  input[:cache].fetch("my:cache:key:v1") do
    # Remove all semicolons from source
    input[:data].gsub(";", "")

return Hash

The processor should return metadata Hash. With the exception of the :data key, the processor can store arbitrary valid JSON values in this Hash. The data will be stored and exposed on Asset#metadata.

The returned :data replaces the assets input[:data] to the next processor in the chain. Returning a String is shorthand for returning { data: str }. And returning nil is shorthand for a no-op where the input data is not transformed, { data: input[:data] }.


The metadata Hash provides an open format for processors to extend the pipeline processor. Internally, built-in processors use it for passing data to each other.

  • :required - A Set of String Asset URIs that the Bundle processor should concatenate together.
  • :stubbed - A Set of String Asset URIs that will be omitted from the :required set.
  • :links - A Set of String Asset URIs that should be compiled along with this asset.
  • :dependencies - A Set of String Cache URIs that should be monitored for caching.
  • :map - An Array of source maps for the asset.
  • :charset - The mime charset for an asset.
def self.call(input)
  # Any metadata may start off as nil, so initialize it the value
  required = Set.new(input[:metadata][:required])

  # Manually add "foo.js" asset uri to our bundle
  required << input[:environment].resolve("foo.js")

  { required: required }

Contributing to Sprockets

Sprockets is the work of hundreds of contributors. You're encouraged to submit pull requests, propose features and discuss issues.


Version History

Please see the CHANGELOG


Sprockets is released under the MIT License.