Search code examples
javascriptcssruby-on-railscomments

Why all comments have no effect of application.css.scss and application.js in rails


I have a weird confusion, when I use application.js in rails like that:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require_tree .
//= require underscore
//= require gmaps/google

and use application.css.scss like that:

/*

 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *
 *= require_tree .
 *= require_self
 */

I think // is a comment in JS file and /* */ is also a comment in CSS file, I didn't think too much and just use before, but for now I wanna know why all comments in JS and CSS file have no effects in rails?


Solution

  • Yes, both // and /* */ are comments for js and css files respectively, but //= and *= are directives used by sprockets, from the docs:

    The DirectiveProcessor is responsible for parsing and evaluating directive comments in a source file.

    A directive comment starts with a comment prefix, followed by an “=”, then the directive name, then any arguments.

    // JavaScript
    //= require "foo"
    
    # CoffeeScript
    #= require "bar"
    
    /* CSS
     *= require "baz"
     */
    

    So js or .css files will treat //= and *= as comments, but sprockets will read those directives to load the required files into the rails asset pipeline.

    Check also the sprockets guides for more detailed information.