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

Rails

Getting Turbolinks to work with Webpack

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

Rails

How to add Tailwind UI to a Rails project

The steps we went through to set Tailwind UI up on an existing Rails project