javascriptruby-on-railsstimulusjs

Can't import a Stimulus component to my Rails application: Uncaught TypeError: Failed to resolve module specifier


Tried to follow te set up guide for this NestedForm Stimulus component: Installation

Like so:

$ npm install stimulus-rails-nested-form --save

app/javascript/controllers/application.js

import { Application } from "@hotwired/stimulus"
import NestedForm from 'stimulus-rails-nested-form' // Added this

const application = Application.start()
application.register('nested-form', NestedForm) // Added this

// Configure Stimulus development experience
application.debug = false
window.Stimulus   = application

export { application }

And I'm getting:

Uncaught TypeError: Failed to resolve module specifier "stimulus-rails-nested-form". Relative references must start with either "/", "./", or "../".

I can see the package properly installed in the node_modules directory and Stimulus is getting loaded properly as I'm using it in other places of the application.

enter image description here

I'm on Rails 7.0.4.

Appreciate any help, cheers!


Solution

  • If you share a bit more about your rails setup that might help.

    Your Rails app might not know about your javascripts... have a look here: https://guides.rubyonrails.org/working_with_javascript_in_rails.html

    You will either need to use importmaps (in which scenario you wouldn't need npm), or you use esbuild or webpack (I would not recommend the latter).