Search code examples
ruby-on-railsreact-railsshakapacker

Uncaught Error: Cannot find module '@hotwired/turbo-rails'


I am using the Shakapacker https://github.com/reactjs/react-rails and I have come across this error despite following all the steps in the Get started with shakapacker section I am not sure why this is happening any help is appreciated

config/importmap.rb

# Pin npm packages by running ./bin/importmap

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"

app/javascript/application.js

import "@hotwired/turbo-rails" 
import "controllers"

picture of error

enter image description here


Solution

  • You're mixing concepts. Shakapacker and Import Maps are 2 different ways of building your front-end.

    • Shakapacker: it's based on webpack, so you are running a Node.js bundler with a compilation/transpilation step. Dependencies are defined in the package.json.
    • Import Maps: based on ESM so it runs directly in the browser with no bundling step. It's the new Rails 7+ default.

    So first of all, you'll need to choose one of the options to build your front-end code (you can probably mix both, but it will be messy if you don't have a clear understanding of how they work). If you just need "Hotwire" and don't want any kind of complex stuff (three-shaking, hot-reloading, ...), the importmap-rails solution is simpler and the recommended way to go.

    There is also a 3rd option (my 🙋‍♂️ preferred one): jsbundling-rails. It's a small layer/glue-code to use a js bundler (esbuild, webpack or rollup) and rely on the Rails assets pipeline (Sprockets) to plug-in into the app. I you want to see an example of this, some time ago I published a ready-to-go template: https://github.com/ralixjs/rails-ralix-tailwind.