Getting Turbolinks to work with Webpack

How to re-add Turbolinks back into a Rails app when moving to Webpack

Migrating a Rails app from using sprockets to webpack can contain a few small gotchas, getting Turbolinks back is one of them.

Normally we get Turbolinks for “free” in Rails apps, it comes set up out of the box. If running an older version of Rails, a rails new will set up Turbolinks in the asset pipeline, a newer version will hook it up with webpack.

If you are migrating an existing app that used the asset pipeline to one that uses webpack, you don’t get turbolinks for free anymore. There are a couple of manual steps.

The first thing we need to do is use yarn to install Turbolinks, not bundle.

  • yarn add turbolinks

This will pull in the appropriate package.

Since we don’t use bundle to manage Turbolinks anymore, we can remove it from our Gemfile

  • Delete gem 'turbolinks' from your Gemfile

Just like how app/assets/javascript/application.js would have imported something related to Turbolinks, so must our app/javascripts/pack/application.js (or whatever your main pack file is named).

  • require("turbolinks").start();in your packfile will get Turbolinks running

For a standard site this should be all you need. If you have other javascript that hooked into Turbolinks functionality then you will need to make sure this has been migrated across into JavaScript that webpack can see.

Recent posts View all

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.

VS Code Web Dev

Select multiple lines in VS Code

How to select multiple lines to edit at once within VS Code