Installing Turbo with the Asset Pipeline

I don’t understand how Turbo is suppose to work with the asset pipeline.

I found this issue here and this one too where DHH suggests adding turbo to the importmap but I have no idea what this means.

I added the Turbo js as a module like this:

javascript_include_tag "turbo", type: "module"

But now I don’t know how to expose the Turbo object globally like it used to be with Turbolinks.

I was wondering about this, too. Maybe it is worth raising an issue in the turbo-rails repo because it looks that it is not possible to expose Turbo (or I’m just lacking some JavaScript knowledge).

Turbo for ESM is meant to be used as an import. So you’ll have to do import { Turbo } from "turbo" in your stimulus controller or elsewhere to use it.

The asset pipeline concatenates all JS files together and so I don’t think this would be compatible with ESM where the import has to be defined at the top of the file (that’s how I understand it at least). And not sure ESM is supported by CoffeeScript.

I guess I could glue it in my app by doing something like this:

javascript_include_tag "turbo", "turbo-loader", "application", type: "module"

The turbo-loader.js would just import Turbo and then put in the global context. I haven’t tried it yet but the drawback is that this sends 3 requests to the server instead of just one and it feels like a bit of a hack.

@dhh It would be great if there was a build of Turbo that could just be dropped in the asset pipeline and linked as //= require turbo. It would expose the Turbo object in the global scope. But I also understand if you prefer to only target modern JS environments with this.

Some of us are stuck with successful legacy projects but still want to use the latest and greatest tech! :wink:

Using Turbo with the asset pipeline is meant to be used without concatenation or transpiling. The asset pipeline is only used the copy and fingerprint assets. Browser is providing the module system.

2 Likes