Sprockets Documentation

repository·main·Indexed 21 days ago

https://github.com/rails/sprockets

A Ruby library for compiling and serving web assets, featuring declarative dependency management and a preprocessor pipeline for JavaScript and CSS. It supports logical paths, directives (require, link, depend_on, stub), and various processors including ERB, Sass/SCSS, CoffeeScript, and Babel.

Tokens
13.7K
Snippets
60
Records
75
Agent score
76%

What's inside Sprockets

  1. Understand Gzip asset generation

    main

    By default, Sprockets automatically generates a gzipped copy for every compiled non-binary asset (such as .css, .js, and .svg files).

    If Sprockets generates: application-12345.css

    It will also produce: application-12345.css.gz

    This behavior can be disabled through your specific framework's configuration.

  2. Understand Sprockets asset logical paths

    main

    Assets are always referenced by their logical path, which is the path of the asset source file relative to its containing directory in the load path.

    Important: When requesting a compiled or transpiled asset, always use the extension of the output file, not the extension of the file on disk. For example, if you have a CoffeeScript file hello.coffee that compiles to JavaScript, you must refer to it as hello.js.

  3. Understand the Source Map mapping format

    main

    The mappings field in a source map uses VLQ (Variable Length Quantity) encoded strings, delimited by commas (,) and semicolons (;).

    • Semicolons (;): Separate groups, where each group represents a line in the generated file.
    • Commas (,): Separate individual segments within a line.
    • Segments: Each segment consists of 1, 4, or 5 variable-length fields.

    VLQ Encoding Details: A single Base64 digit contains 6 bits of data. In the source map specification, the bits are structured as follows:

    • Bit 1: Continuation bit (indicates if more digits follow).
    • Bit 2: Sign bit.
    • Bits 3-6: The actual value.

    Example bit structure:

       Continuation
       |    Sign
       |    |
       V    V
       101011
  4. Specify processors through file extensions

    main

    Sprockets uses filename extensions to determine which processors to run and in what order. Processors are run from right to left (tail to head).

    For example, a file named application.scss.erb will first run the erb processor and then the scss processor. When requesting the compiled file, always ask for the desired output extension (e.g., application.css).

    application.scss.erb
  5. Understand the Sprockets cache

    main

    Sprockets uses a cache (typically in tmp/cache/assets) to store intermediary compiled files. This speeds up compilation by allowing Sprockets to reuse parts of an asset that haven't changed.

    If you encounter unexpected behavior or bugs, you may need to clear the cache. In Rails, you can force a clean install by deleting the public/assets and tmp/cache/assets directories.

  6. Understand the Sprockets asset pipeline architecture

    main

    The Sprockets asset pipeline is a collection of components designed to manage, compile, and serve client-side assets in a Rails application. It solves the problem of organizing assets (moving them from the public folder to app/assets, lib/assets, and vendor/assets) and balancing code organization with performance (handling technologies like SASS, CoffeeScript, and ES6).

    The pipeline is composed of several key layers:

    1. Sprockets: The core engine that enables compiling and serving assets. It defines a processor pipeline that can be extended.
    2. Processors: Responsible for transforming asset content (e.g., compiling SASS to CSS).
    3. Transformers: Modify the asset content.
    4. Compressors: Reduce file size for production (e.g., minification).
    5. Directives: Instructions within asset files that control how they are processed and bundled.
    6. Environment: The context in which assets are compiled and served.

    In a typical Rails setup, the pipeline is powered by a suite of gems including sprockets, sprockets-rails, sass-rails, execjs, and coffee-rails.

  7. How Sprockets processors work

    main

    Processors are the core components of Sprockets. Every piece of functionality is implemented as a processor. A processor is any call-able object (like a Ruby object responding to .call or a lambda) that accepts an input hash and returns a hash containing processed data and optional metadata.

    Input Hash Keys

    When a processor is called, it receives a hash containing:

    • :data: The string contents of the asset
    • :environment: The current Sprockets::Environment instance
    • :cache: The Sprockets::Cache instance
    • :uri: The asset URI
    • :source_path: The full path to the original file
    • :load_path: The current load path for the file
    • :name: The logical name of the file
    • :content_type: The MIME type of the output asset
    • :metadata: A Hash of processor metadata

    Return Hash Keys

    A processor must return a hash containing:

    • :data: The processed string content (replaces input[:data] for the next processor in the chain)
    • :required: A Set of String asset URIs that the BundlerProcessor should concatenate
    • :stubbed: A Set of String asset URIs to be omitted from the :required set
    • :links: A Set of String asset URIs that should be compiled along with the assets
    • :dependencies: A Set of String cache URIs to be monitored for caching
    • :map: An Array of source maps for the assets
    • :charset: The MIME charset for an asset
    # Example of a minimal Ruby sprockets processor
    -> (input) {
      data = input[:data].gsub(';', '')
      { data: data }
    }
  8. How source maps are detected in assets

    main

    Browsers detect source maps by looking for a specific comment at the end of an asset file. When this comment is present, the browser makes an additional request to the specified location to retrieve the mapping data.

    JavaScript Source Maps

    JavaScript files use a comment starting with //# sourceMappingURL=.

    Examples:

    • Full path: //# sourceMappingURL=/assets/application.js.map
    • Relative path: //# sourceMappingURL=application.js.map

    CSS Source Maps

    CSS files use a different comment specification: /*# sourceMappingURL=application.css.map */

    //# sourceMappingURL=application.js.map
    /*# sourceMappingURL=application.css.map */
  9. Integrate Sprockets with Rails using sprockets-rails

    main

    The sprockets-rails gem integrates Sprockets into a Rails application by providing helpers and automatic configuration.

    Rails Helpers

    Use these helpers in your templates to include assets:

    • javascript_include_tag
    • stylesheet_link_tag

    Error Handling

    In development, sprockets-rails will raise a Sprockets::Rails::Helper::AssetNotPrecompiled exception if you attempt to use an asset that has not been included in the precompile list/manifest.

    <%= javascript_include_tag 'foo' %>
  10. Use Sass with Rails via sass-rails

    main

    While SassProcessor is built into Sprockets, the sass-rails gem provides necessary integration for Rails, including:

    • Generators for creating Sass files during scaffolding.
    • An importer that supports glob imports and ERB within Sass files.

    Example of supported Sass syntax:

    @import "foo/*"
    // bar.scss.erb
    @import "bar"
  11. Style assets with Sass and SCSS

    main

    If the sass gem is available, Sprockets supports Sass syntax.

    • Use .sass for the original whitespace-sensitive syntax.
    • Use .scss for the SCSS syntax.

    When referencing these assets (e.g., in Rails), always specify the target extension you want to serve (usually .css). Sprockets will handle the conversion from .scss to .css automatically.

    <%# Referencing a scss file in Rails %>
    <%= asset_path("foo.css") %>
  12. Use JavaScript templates with EJS or Eco

    main

    Sprockets supports JavaScript templates for client-side rendering using the .jst extension. These templates are compiled into JavaScript functions and made available on the global JST object, keyed by their logical path.

    • EJS: Use the .jst.ejs extension. Requires the ejs gem.
    • Eco: Use the .jst.eco extension. Requires the eco gem (which depends on CoffeeScript).

    To use a template, require it in your JavaScript files and then invoke the function via JST["path/to/template"].

    // templates/hello.jst.ejs
    <div>Hello, <span><%= name %></span>!</div>
    
    // application.js
    //= require templates/hello
    // Access via the global JST object
    $("#hello").html(JST["templates/hello"]({ name: "Sam" }));