How to use stimulus components with rails import maps

1.6k views Asked by At

I want to include this stimulus component into my brand new rails 7 app: https://www.stimulus-components.com/docs/stimulus-dropdown

When I follow their setup approach, i get the following error in my browser console: platforms#:1 Uncaught TypeError: Failed to resolve module specifier "stimulus-dropdown". Relative references must start with either "/", "./", or "../".

I found this article on stackoverflow: Failed to resolve module specifier "stimulus-autocomplete"

which suggests to add a "pin" to my importmap.rb.

So i took the dropdown link from here https://www.jsdelivr.com/package/npm/stimulus-dropdown

and put it into my importmap.rb by:

pin "stimulus-dropdown", to: "https://cdn.jsdelivr.net/npm/[email protected]/dist/stimulus-dropdown.min.js"

But it doesnt work and displays a 404 in my browser console.

I hope someone can help, there must be an easy way to use stimulus-components in a brand new rails 7 app.

2

There are 2 answers

1
JP Silvashy On

I suggest adding it with yarn as well with yarn add stimulus-dropdown. This worked for me when I faced your issue.

0
Atekelt Afework On

i was also struggling but i have figured it out

first run -

./bin/importmap pin stimulus-dropdown

second create a stimulus controller called 'dropdown' -

rails g stimulus dropdown

then copy-paste the following code into the dropdown controller

import { Application } from '@hotwired/stimulus'
 import Dropdown from 'stimulus-dropdown'

 const application = Application.start()
 application.register('dropdown', Dropdown)

After you do all the above you are ready to use stimulus drop-down in your views. for the view example check the docs on the site.