Skip to content

Using Webpacker to compile javascript assets

Justin Coyne edited this page Oct 30, 2020 · 19 revisions

This is a work in progress. And should be considered experimental.

Installing Webpacker in Blacklight

This requires Blacklight 7 or higher.

These instructions will show you how to use Webpacker with Blacklight in development mode. They have been tested on as of October 2020. The Webpacker gem will replace the entire sprockets based asset pipeline.

Here's what to do:

  1. Install nodejs and npm (they are packaged together)
  2. Install yarn
  3. Add gem 'webpacker', '~> 5.2' to your Gemfile
  4. Run bundle install (add --without production test to set development mode and not install production/test gems like mysql2)
  5. Run bundle exec rails webpacker:install
  6. Run:
yarn add blacklight-frontend
yarn add popper.js
yarn add @rails/ujs
yarn add jquery

Next, change config/webpack/environment.js as per https://getbootstrap.com/docs/4.0/getting-started/webpack/ and https://github.com/rails/webpacker/blob/master/docs/webpack.md#plugins to this:

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

environment.plugins.prepend(
    'Provide',
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery',
        Popper: ['popper.js', 'default'],
        Rails: ['@rails/ujs'],
    })
)


module.exports = environment

In your pack file (app/javascript/packs/application.js), require blacklight, popper, bootstrap and an in-lined block of JS from a erb file:

// Vendor
require('@rails/ujs').start()
global.Rails = Rails

import "bootstrap/dist/js/bootstrap"
import 'blacklight-frontend/app/assets/javascripts/blacklight/blacklight'

You may delete the contents of app/assets/javascripts as these are no longer being used.

Using Webpacker in Blacklight Development

Run bin/webpack-dev-server to have webpacker compile new JavaScript packs (and other assets) on change. Webpacker will also refresh your browser page when this dev server is running.

Add front end javascript dependencies with yarn add package followed by yarn to intall said package. yarn add package will update your package.json, yarn will update your yarn.lock. Note that you probably need to shut off the webpack dev server and rails server when you're adding new packages.

Stuff on the Internet about rails and webpacker

Clone this wiki locally