Skip to content

Using Sprockets to compile javascript assets

Jane Sandberg edited this page Jul 12, 2022 · 5 revisions

By default (in Blacklight 7) the assets generator adds the following things to your application to enable Sprockets to build a javascript bundle:

Added to the Gemfile:

gem 'bootstrap', '~> 4.0'
gem 'popper_js'
gem 'twitter-typeahead-rails', '0.11.1.pre.corejavascript'

These requires are injected into app/assets/javascripts/application.js:

//= require jquery3
//= require popper
//= require twitter/typeahead
//= require bootstrap

If you are using Uglifier in production (rails default) and you encounter this error:

Uglifier::Error: Unexpected token: operator (>). To use ES6 syntax, harmony mode must be enabled with Uglifier.new(:harmony => true).

Then change this line in config/environments/production.rb:

  config.assets.js_compressor = :uglifier

to

  config.assets.js_compressor = Uglifier.new(harmony: true)

Customization Options

Blacklight 7 provides a pre-compiled JavaScript at (/app/assets/javascripts/blacklight/blacklight.js), which is compiled from the source files in app/javascript/blacklight. If you need fine-grained control over this process, you can override it for Sprockets by adding the "source path" to your application's asset path, and creating a custom app/assets/javascripts/blacklight/blacklight.js.

for example, in config/initializers/assets.rb you can put

bl_dir = Bundler.rubygems.find_name('blacklight').first.full_gem_path
assets_path = File.join(bl_dir, 'app', 'javascript')
Rails.application.config.assets.paths << assets_path

And, as an example, if you wanted to remove the 'autocomplete.js' from the compilation, your app/assets/javascripts/blacklight/blacklight.js could look like this:

//= require 'blacklight/core.js'
//= require 'blacklight/bookmark_toggle.js'
//= require 'blacklight/button_focus.js'
//= require 'blacklight/checkbox_submit.js'
//= require 'blacklight/facet_load.js'
//= require 'blacklight/modal.js'
//= require 'blacklight/search_context.js'

Note that, when you update Blacklight versions, the available source files may change, so you might need to revisit this file from time to time.

Also note that the most recent Blacklight versions include ES2020 features. If you are customizing the javascript functionality, you may see errors like Uglifier::Error: Unexpected token: punc (.) and need to consider migrating from uglifier to terser.