Hotwire Discussion

Turbo drive with Stimulus getting "Turbo is not defined"

I am trying to make Turbo.visit work inside a Stimulus controller without using a js build system like webpack.

Here is my html head:

<head>
    <script type="module">import hotwiredTurbo from 'https://cdn.skypack.dev/@hotwired/turbo';</script>
    <script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
    <script src="/static/js/controllers/dropdown_controller.js"></script>
    <script src="/static/js/controllers/visit_controller.js"></script>
</head>

And here is my Stimulus controller:

(() => {
    const application = Stimulus.Application.start()

    application.register("visit", class extends Stimulus.Controller {
        static get targets() {
            return ["dropdownItem", "userinput", "ddContent"]
        };
        go() {
            Turbo.clearCache();
            Turbo.visit("/hello");
        };
    })
})()

And I get a Turbo is not defined. I must be doing something wrong with the imports because the controller code is correct.

It seems you’re importing hotwiredTurbo from the package but refereing to it as Turbo. Perhaps do:

import Turbo from "@hotwired/turbo"

Thanks! I did the change like below but it still gives me the same error.

<head>
    <script type="module">import Turbo from 'https://cdn.skypack.dev/@hotwired/turbo';</script>
    <script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
    <script src="/static/js/controllers/dropdown_controller.js"></script>
    <script src="/static/js/controllers/visit_controller.js"></script>
</head>

I’ve seen other suggest:

    <script type="module">
      import * as Turbo from 'https://cdn.skypack.dev/@hotwired/turbo';
      window.Turbo = Turbo;
    </script>
1 Like

Thank you all for your answers. I ended up implementing webpack. The docs on running w/o a build system are not yet super clear and setting up webpack was half an hour of work.

Thank you @tleish – this approach worked for me when trying to use both Stimulus and Turbo via Skypack. Although oddly (?) given @kfk’s experience, it doesn’t seem to be necessary to do the same for Turbo at this point.

<script type="module">
  import Turbo from 'https://cdn.skypack.dev/@hotwired/turbo';
  import * as Stimulus from 'https://cdn.skypack.dev/stimulus';
  window.Stimulus = Stimulus;
</script>

@leoc - you are correct, starting with v7.0.0-beta.6 release it now sets window.Turbo “automatically on import to accommodate the needs of the native mobile adapters and ease of use”

1 Like