Rails

Requiring JavaScript & Stylesheets with Requirejs & Sprockets

Demo for requiring JavaScript and Stylesheets in Ruby on Rails:

1. Create a new rails project:

$ rails new demo --skip-bundle
$ cd demo

2. Edit Gemfile and install bundle:

Most important ones being:

  1. requirejs-rails
    • requirejs-rails provides namespace support for javascript dependencies, something sprockets cannot achieve
  2. sprockets:
    • sprockets is used to require stylesheets here. Its doc specifies that 3.0 and above doesn’t support LESS, but if you don’t mind using SCSS you could bypass the version specification
## Gemfile
## Edit the following lines

## Use LESS for stylesheets, optional
gem 'therubyracer'
gem 'less-rails'

## For dependencies
gem 'requirejs-rails'
gem 'sprockets', '2.12.0'

Save file and update/install bundles.

$ bundle update
$ bundle install

3. Generate a controller, and start server:

$ rails g controller welcome index
# config/routes.rb
# uncomment this line:

root 'welcome#index'
$ rails server

Now you could see the blank welcome page at localhost:3000.

4. Add the line of requirement:

# app/views/layout/welcome.html.erb
# change the line containing javascript_include_tag into:

<%= requirejs_include_tag "welcome" %>

Note that:

  • it’s requirejs_include_tag instead of javascript_include_tag
  • keeping "data-turbolinks-track" => true in the requirjs tag causes error

4. Finally, delete all the old stuff created by Sprockets and start requiring and defining!

Here we still have some //=require formatted old requirements generated by Sprockets, but they will only cause chaos now. From now on we will only use requirejs-rails to require javascript files.

# app/assets/javascripts/application.js
# => rename to application.js.coffee and delete everything inside
# require jquery and see console spilling it out willingly 

require ['jquery'], ($) ->
  console.log $

JQuery module is included in rails by default, but if you want to include other libraries, put them in app/assets/javascripts/ or vendor/assets/stylesheets and require them like above.

5. Now, time for requiring Stylesheets:

This is more straightforward with Sprockets.

a. Supported Comment Types:

/* Multi-line comment blocks (CSS, LESS, SCSS)
 *= require foo
 */

// Single-line comment blocks (LESS, SCSS)
//= require foo

b. Available File Types:

  1. foo.css
  2. foo.css.less
  3. foo.less
  4. foo.scss
  5. foo.css.scss

c. Priority of Directories:

  1. lib/assets/stylesheets
  2. vendor/assets/stylesheets

Which means that putting your style files in either of the directories would do, but if there are files with the same name, it’ll be the one under app/.

Standard

Leave a Reply