'Hotwire Rails - Cannot use import statement outside a module

I have installed hotwire-rails in an existing Rails project. Before even writing any hotwire related code I get the following error on the browser console on every page:

Uncaught SyntaxError: Cannot use import statement outside a module in application.debug-86...95.js:53462

The line that the error is referring to is this:

import { Controller } from "@hotwired/stimulus"

I am using Rails 6.1.3.1 with Sprockets for the assets, I have only used hotwire in Rails projects using webpack before so unsure if this has something to do with it.



Solution 1:[1]

In Rails 7, turbo comes prepackaged with a few gems that you need to install manually if you're using Rails 6.

1/ Install gem importmap-rails

2/ Install gem stimulus-rails

This should solve your issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samuel Faure